phparraysmultidimensional-arraygroupingsub-array

Group rows of a 2d array by a column value and push whole rows as child elements per group


I have an array like which is sorted by category

$array = [
    ['name' => 'JOHN', 'category' => 'abc'],
    ['name' => 'JOHN', 'category' => 'abc'],
    ['name' => 'JOHN', 'category' => 'abc'],
    ['name' => 'John6', 'category' => 'cvb'],
    ['name' => 'John6', 'category' => 'cvb'],
    ['name' => 'Outfit7', 'category' => 'cvb'],
    ['name' => 'John6', 'category' => 'cvb'],
    ['name' => 'Joh8', 'category' => 'fgh'],
    ['name' => 'JOHN', 'category' => 'fgh'],
    ['name' => 'John9', 'category' => 'fgh'],
    ['name' => 'JOHN', 'category' => 'fgh'],
    ['name' => 'John0', 'category' => 'fgh'],
    ['name' => 'Johny', 'category' => 'fgh'],
]

Now I want to this array deep multidimensional array from category means some thing like:

[
    'abc' => [
        ['name' => 'JOHN', 'category' => 'abc'],
        ['name' => 'JOHN', 'category' => 'abc'],
        ['name' => 'JOHN', 'category' => 'abc'],
    ],
    'cvb' => [
        ['name' => 'John6', 'category' => 'cvb'],
        ['name' => 'John6', 'category' => 'cvb'],
        ['name' => 'Outfit7', 'category' => 'cvb'],
        ['name' => 'John6', 'category' => 'cvb'],
    ],
    'fgh' => [
        ['name' => 'Joh8', 'category' => 'fgh'],
        ['name' => 'JOHN', 'category' => 'fgh'],
        ['name' => 'John9', 'category' => 'fgh'],
        ['name' => 'JOHN', 'category' => 'fgh'],
        ['name' => 'John0', 'category' => 'fgh'],
        ['name' => 'Johny', 'category' => 'fgh'],
    ],
];

Solution

  • Try this:

    $tmp = ' ' ;
    
    $new_Array = array();
    
        foreach($category_array as $cat_id => $cat)
        {
           $tmp = $cat['category'];  
           $new_array[$tmp][$cat_id] = $cat;
        }