Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to group array by subarray values in PHP

1 Answer

0 votes
$array = [['id' => 133, 'name' => 'aaa', 'group' => 'A'], 
          ['id' => 265, 'name' => 'www', 'group' => 'B'], 
          ['id' => 387, 'name' => 'ppp', 'group' => 'A'], 
          ['id' => 490, 'name' => 'mmm', 'group' => 'B']];

$grouped_array = array_reduce(
    $array,
    function ($carry, $item) {
        $carry[$item['group']][] = $item;
        return $carry;
    },
    []
);

print_r($grouped_array);




/*
run:

Array
(
    [A] => Array
        (
            [0] => Array
                (
                    [id] => 133
                    [name] => aaa
                    [group] => A
                )

            [1] => Array
                (
                    [id] => 387
                    [name] => ppp
                    [group] => A
                )

        )

    [B] => Array
        (
            [0] => Array
                (
                    [id] => 265
                    [name] => www
                    [group] => B
                )

            [1] => Array
                (
                    [id] => 490
                    [name] => mmm
                    [group] => B
                )

        )

)

*/

 



answered Dec 9, 2023 by avibootz
...