Search code examples
phparraysmultidimensional-arraycountmultiple-matches

Count matches in array of arrays PHP


Array
(
    [0] => Array
    (
        [song] => More Than A Feeling
        [artist] => Not Boston
        [time] => 15:00
    )

    [1] => Array
    (
        [song] => More Than A Feeling
        [artist] => Boston
        [time] => 11:20
    )
    [2] => Array
    (
        [song] => More Than A Feeling
        [artist] => Boston
        [time] => 15:23
    )
)

Have an array of arrays like this. I am trying to count all matches. Right now i'm using

array_count_values(array_column($arr, 'song'));

That's good but it counts songs if the artist doesn't match. I am trying to output the following.

Array
    (
    [0] => Array
    (
        [song] => More Than A Feeling
        [artist] => Not Boston
        [count] => 1
    )

    [1] => Array
    (
        [song] => More Than A Feeling
        [artist] => Boston
        [count] => 2
    )
)

Not sure where to start. Thanks for the help!


Solution

  • Found the answer on a different question. This worked for me.

    $arr = array(0 => array('song' => 'More Than A Feeling', 'artist' => 'Not Boston', 'time' => 0), 
               1 => array('song' => 'More Than A Feeling', 'artist' => 'Boston', 'time' => 0), 
               2 => array('song' => 'More Than A Feeling', 'artist' => 'Boston', 'time' => 0));
    
    
    $hash = array();
    $array_out = array();
    
    foreach($arr as $item) {
        $hash_key = $item['song'].'|'.$item['artist'];
        if(!array_key_exists($hash_key, $hash)) {
            $hash[$hash_key] = sizeof($array_out);
            array_push($array_out, array(
                'song' => $item['song'],
                'artist' => $item['artist'],
                'count' => 0,
        ));
    }
    $array_out[$hash[$hash_key]]['count'] += 1;
    

    }

     var_dump($array_out);