Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Counting similar occurrences in multidimensional array

Tags:

arrays

php

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().

like image 415
anders Avatar asked Mar 08 '26 17:03

anders


1 Answers

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);
like image 61
motanelu Avatar answered Mar 10 '26 07:03

motanelu