0

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

1
  • Do you want to add only values of the array having "vote" as a key? Commented Oct 31, 2016 at 1:15

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

To add the values of vote you can do as follows:

array_sum(array_column($array[1], 'vote'));

Comments

0

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;
        }
    }
}

Comments

0

demo here:

<?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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.