phparraysmultidimensional-arraygrouping

Group a 2d array by a column and remove the grouping column from the grouped subarrays


Given my Array

array [0]
    fielda: cca
    fieldb: my value b
    fieldc: my value c
    fieldd: my value d

array [1]
    fielda: cca
    fieldb: my value b
    fieldc: my value c
    fieldd: my value d

array [2]
    fielda: cca
    fieldb: my value b
    fieldc: my value c
    fieldd: my value d

array [3]
    fielda: ccb
    fieldb: my value b
    fieldc: my value c
    fieldd: my value d

array [4]
    fielda: ccb
    fieldb: my value b
    fieldc: my value c
    fieldd: my value d

Is there a simple way to restructure it so that fielda is grouped like so

array [0]
    fielda: cca
        array [0]
            fieldb: my value b
            fieldc: my value c
            fieldd: my value d
        array [1]           
            fieldb: my value b
            fieldc: my value c
            fieldd: my value d
        array [2]                   
            fieldb: my value b
            fieldc: my value c
            fieldd: my value d
        array [3]                   

array [1]
    fielda: ccb
        array [0]
            fieldb: my value b
            fieldc: my value c
            fieldd: my value d
        array [1]           
            fieldb: my value b
            fieldc: my value c
            fieldd: my value d

Solution

  • Maybe there's a simpler way, but this should work for you:

    $new_array = array();
    foreach ($array as $values) // $array is your original array
    {
        $new_array[array_shift($values)][] = $values;
    }
    print_r($new_array);
    

    DEMO: http://codepad.org/M26yBLL4