-1

My controller is returning a time-series array for a graph, it also needs the total views count. The array it returns is in this format, need to calculate the sum of views corresponding ot the dates.

framework: Laravel

[
    {
        "2021-04-30": 0,
        "2021-05-01": 0,
        "2021-05-02": 0,
        "2021-05-03": 0,
        "2021-05-04": 0,
        "2021-05-05": 0,
        "2021-05-06": 1
    }
]

$result = $as->getVisits();
        $array = json_decode($result,1);
        $total = 0;
        foreach($array[0] as $date => $visits)
            $total += 1;
        echo $total;
        return [$result, $total];
Varun Haridas
  • 77
  • 1
  • 1
  • 8
  • Does this answer your question? [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – El_Vanja May 06 '21 at 09:59
  • What have you tried to perform this task? It seems pretty straightforward. The proposed duplicate explains how to obtain those values, summing them should be easy afterwards. – El_Vanja May 06 '21 at 10:00

1 Answers1

0

This look like a JSON array, you need first to decode it in a php array and then loop it to make the sum if you want to control over the dates

$array = json_decode($json,1);

$sumVisits = 0;
foreach($array[0] as $date => $visits)
   $sumVisits += 1;
echo $sumVisits;

Or if you just want to sum everything you can use array_sum as pointed out in the comments by El_Vanja

$array = json_decode($json,1);
echo array_sum(array[0]);
Lucarnosky
  • 514
  • 4
  • 18
  • [Test your code](https://3v4l.org/Q40F8) before posting an answer. Aside from that, `array_sum` is available in PHP, no need to manually loop. – El_Vanja May 06 '21 at 09:59
  • Edit the code, I use the foreach because this can give to the user the possibility to handle by dates.Thanks for the link of not working code. – Lucarnosky May 06 '21 at 10:03
  • but I'm getting errors for JSON decode like you guys gave, attaching code-snippet to the question – Varun Haridas May 06 '21 at 10:54
  • Which kind of error? I don't think is related with this piece of code, you can check it [here](https://3v4l.org/sIbrd) – Lucarnosky May 06 '21 at 12:37