I have a multidimensional array, in which I want to count similar occurrences.
So basically I want this:
[
[
'type' => 'frosties',
'madeby' => 'kelloggs'
],
[
'type' => 'frosties',
'madeby' => 'kelloggs'
],
[
'type' => 'cornflakes',
'madeby' => 'kelloggs'
]
];
To end out as this:
[
[
'type' => 'frosties',
'madeby' => 'kelloggs',
'count' => 2
],
[
'type' => 'cornflakes',
'madeby' => 'kelloggs',
'count' => 1
]
]
This is what I've come up with so far:
public function count($array) {
$newArr = [];
foreach ($array as $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
];
}
}
return $newArr;
}
I might have been staring at this for too long, but I just can't seem to come up with what goes inside the if().
Here you go:
$array = [
[
'type' => 'frosties',
'madeby' => 'kelloggs'
],
[
'type' => 'frosties',
'madeby' => 'kelloggs'
],
[
'type' => 'cornflakes',
'madeby' => 'kelloggs'
]
];
$results = [];
foreach ($array as $pair) {
//ksort($pair); <- might need ksort here if type and madeby are not in the 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With