php中的Array_sum - 所有值

问题描述:

I wanna sum all values from my array for example

{
  "data": [
    {
      "message_count": 14051
    },
    {
      "message_count": 12731
    },
    {
      "message_count": 7867
    },
    {
      "message_count": 6053
    },
    {
      "message_count": 4
    }
  ]
}

and that's my code:

<?php
$messages_count = file_get_contents('baza.html');
$json_a=json_decode($messages_count,true);
$counting_base = ($json_a['data']);
echo array_sum($counting_base);
?>

but I still get '0'. Any ideas? Thank you very much

This is because your array is two-dimensional. array_sum() requires a one-dimensional array. To make it one-dimensional, loop through the array, and use array_sum(), like so:

$new = array();
foreach ($json_a['data'] as $key => $innerArr) {
    $new[] = $innerArr['message_count'];
}

echo array_sum($new); // 40706

Online demo

Try this:

array_sum(array_column($json_a['data'], 'message_count'));

Output: 40706

live demo

alternative:

You can do it by a loop:

array_sum()

will not be working since you do not right formated array(1D array).

$sum = 0;
for($i=0; $i<count($counting_base); $i++)
{
    $sum += $counting_base['message_count']; 
}

echo "Total = ". $sum;