PHP: Counting similar occurences in multidimensional array -
PHP: Counting similar occurences in multidimensional array -
hello!
i have multidimentional array, in want count similar occurences.
so basicly want this:
[ [ 'type' => 'frosties', 'madeby' => 'kelloggs' ], [ 'type' => 'frosties', 'madeby' => 'kelloggs' ], [ 'type' => 'cornflakes', 'madeby' => 'kelloggs' ] ];
to end out this:
[ [ 'type' => 'frosties', 'madeby' => 'kelloggs', 'count' => 2 ], [ 'type' => 'cornflakes', 'madeby' => 'kelloggs', 'count' => 1 ] ]
this i've come far:
public function count($array) { $newarr = []; foreach ($array $breakfast) { if (in_array($breakfast['type'], $newarr) && in_array($breakfast['madeby'], $newarr)) { //what goes here? //dosomething['count']++; } else { $newarr[] = [ 'type' => $breakfast['type'], 'madeby' => $breakfast['madeby'], 'count' => 0 ]; } } homecoming $newarr; }
i might have been staring @ long, can't seem come goes within if().
thanks in advance guys.
here go:
$array = [ [ 'type' => 'frosties', 'madeby' => 'kelloggs' ], [ 'type' => 'frosties', 'madeby' => 'kelloggs' ], [ 'type' => 'cornflakes', 'madeby' => 'kelloggs' ] ]; $results = []; foreach ($array $pair) { //ksort($pair); <- might need ksort here if type , madeby not in same order. $key = serialize($pair); if (isset($results[$key])) { $results[$key]['count']++; } else { $results[$key] = array_merge($pair, ['count' => 1]); } } $results = array_values($results); print_r($results);
php arrays
Comments
Post a Comment