Search code examples
phparraysmultidimensional-arraygroupingsub-array

Group 2d array data by one column and create a subarray from another column per group


I have an array like this one:

$toGroup = array(
    1 => 
        [
            'value' =>  8000,
            'key'   => 1007
        ],
    2 => 
        [
            'value' => 8001,
            'key'   => 1007
        ],
    3 => 
        [
            'value' => 8002,
            'key'   => 1013
        ],
);

I want to group and restructure it like this:

$toGroup = array(
    1007 => 
        [
            [0] =>  8000,
            [1] =>  8001
        ],
    1013 => 
        [
            [0] => 8002
        ]
);

It should work for a random amount of different entries (different keys/values).


Solution

  • How about something like this?

    //A new array to move the data to.
    var $result = array();
    
    //Loop through the original array, and put all the data
    //into result with the correct structure.
    foreach($toSort as $e) {
        //If this key is not set yet, then create an empty array for it.
        if(!isset($result[$e['key']])) $result[$e['key']] = array()
        //Add the value to the end of the array.
        $result[$e['key']][] = $e['value'];
    }
    
     //Sort the result, based on the key and not the value.
     //If you want it to be based on value, just use sort() instead.
     ksort($result)
    
     //If you want the sub-arrays sorted as well, loop through the array and sort them.
     foreach($result as $e)
         sort($e);
    

    Disclaimar: I have not tested this code.