0

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

1
  • add the output of $counting_base Commented Mar 2, 2014 at 13:31

2 Answers 2

4

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

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

Comments

2

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;

1 Comment

@user2527983: see my top answer

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.