Reputation: 103
I have a array in php that is like this
Array
(
[0] => Array
(
[user] => 1
)
)
Array
(
[0] => Array
(
[vote] => 3.0
)
[1] => Array
(
[vote] => 5.0
)
)
I need to add together the values of vote ( 3.0 + 5.0 = 8) in the array
what is the best way to do this in php
Upvotes: 0
Views: 34
Reputation: 28529
<?php $arrays = array(array(array('user' => 1)), array(array('vote' => 3.0), array( 'vote' => 5.0)));
var_dump(array_map(function($array){return array_sum(array_map(function($value){return $value['vote'] ? $value['vote'] : 0;}, $array));}, $arrays));
Upvotes: 0
Reputation: 665
Try this one:
//assuming $array is your array...
$score = 0;
foreach($array[1] as $element)
{
foreach($element as $key=>$val)
{
if('vote'==$key)
{
$score+=$val;
}
}
}
Upvotes: 0
Reputation: 940
To add the values of vote you can do as follows:
array_sum(array_column($array[1], 'vote'));
Upvotes: 1
Reputation: 23
Maybe you can use this:
$sum = $the_second_array[0];
for($i=1; $i<count($the_second_array); $i++){
$sum += $the_second_array[$i];
}
Add first index value into temporary, then looping from second index of array for sum the next value.
Upvotes: 1