Astha
Astha

Reputation: 1734

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'],
    ],
];

Upvotes: -1

Views: 117

Answers (1)

Rikesh
Rikesh

Reputation: 26451

Try this:

$tmp = ' ' ;

$new_Array = array();

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

Upvotes: 1

Related Questions