Search code examples
phparraysmultidimensional-arraygroupingcounting

Group and count identical rows in a 2d array


I am trying the group display values in a php array with how many times was duplicated in it.

Example:

[
    [6],
    [6],
    [6],
    [5,1],
    [3,3],
    [3,3],
    [3,2,1]
]

What I need as a result is the group of array and the count of them like this:

[[6],3],
[[5,1],1],
[[3,3],2],
[[3,2,1],1],

any type ?

EDIT

I tried to do it with this statement:

$result = array();
foreach ($myarray as $element) {
    $result[$element[0]][] = $element;
}

but I get the result as this:

{"6":[[6],[6],[6]],"5":[[5,1]],"3":[[3,3],[3,3],[3,2,1]]}

The problem is on the 3 group, I need to group [3,3] and [3,2,1] separately.


Solution

  • This seems to to do what you have asked.

    <?php
        //This is your array of elements
        $array = [[6],[6],[6],[5,1],[3,3],[3,3],[3,2,1]];
    
        //This is a list of items that the program knows about, and their position
        $known_items = array();
    
        //For all the elements
        foreach($array as $item){
            //Sort the array to be in ascending order so that any combination will work
            asort($item);
    
            //We only want the item array to have values, and not keys
            $item = array_values( $item );
    
            //Make the content of this item a string so we can use it as a key in arrays
            $arrString = json_encode( $item );
    
            //Have we seen this item before?
            if( array_key_exists( $arrString , $known_items ) ){
                //Yes we have, increase the count
                $known_items[ $arrString ][1]++;
            } else {
                //No we haven't. Add it and start the count as 1
                $known_items[ $arrString ] = [ $item, 1 ];
            }
    
        }
    
        echo json_encode( array_values( $known_items), JSON_PRETTY_PRINT);