JSON Count keys

Skythrust

Member
Jul 9, 2019
132
7
Hi guys,

I am looking for a solution to count keys in a foreach

like how many counts value A, B and C have and D, E and F.


JSON:
$json = '[{"Name":"A","Count":"3"},{"Name":"B","Count":"9"},{"Name":"C","Count":"1"},{"Name":"D","Count":"1"},{"Name":"E","Count":"4"},{"Name":"F","Count":"7"}]'

I am able to echo the name and count via a foreach, and I have tried to use and IF statement like the example below;

PHP:
<?php
   
$data = (json_decode($response, true));

foreach($data['tags'] as $record) {
    if($record['name'] == "A" || $record['name'] == "B" || $record['name'] == "C" ||)
    {count($record['count'])}
//  echo   $record['name']. ' - '. $record['count']. '<br>';

}

?>

Any idea how I can count the values to get this work?
 
Last edited:

Mythraus

dunater
Jul 30, 2012
10
0
Provided I'm understanding this correctly you want to sum the A,B,C and D,E,F values.

The best method for this would be to reduce the current data into an associative array indexed by key and then sum manually from there. The snippet below implements the described behaviour.

PHP:
<?php

$json = '[{"Name":"A","Count":"3"},{"Name":"B","Count":"9"},{"Name":"C","Count":"1"},{"Name":"D","Count":"1"},{"Name":"E","Count":"4"},{"Name":"F","Count":"7"}]';

$data = json_decode($json);

// Reduce Method
$counts_reduce = array_reduce($data, function ($acc, $item) {
  if (!isset($acc[$item->Name])) {
    $acc[$item->Name] = 0;
  }

  $acc[$item->Name] += intval($item->Count);

  return $acc;
}, array());


// Iterative Method
$counts_iter = array();

foreach($data as $item) {
  if (!isset($counts_iter[$item->Name])) {
    $counts_iter[$item->Name] = 0;
  }

  $counts_iter[$item->Name] += intval($item->Count);
}

// Can optionally use '??' with each item to ensure 0 is used as a default
$abc = $counts_reduce["A"] + $counts_reduce["B"] + $counts_reduce["C"];

$def = $counts_reduce["D"] + $counts_reduce["E"] + $counts_reduce["F"];

var_dump([
  "counts_reduce" => $counts_reduce,
  "counts_iter" => $counts_iter,
  "abc" => $abc,
  "def" => $def
]);
 

Users who are viewing this thread

Top