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 rows in an associative array by column in PHP

1 Answer

0 votes
$array = [
    'a' => ['id' => 4, 'name' => 'vvv'],
    'b' => ['id' => 3, 'name' => 'qqq'],
    'c' => ['id' => 2, 'name' => 'ooo'],
    'd' => ['id' => 3, 'name' => 'ppp'],
    'e' => ['id' => 2, 'name' => 'www'],
    'f' => ['id' => 5, 'name' => 'mmm'],
    'g' => ['id' => 5, 'name' => 'zzz']
];

$grouped_array = [];

foreach ($array as $key => $item) {
   $grouped_array[$item['id']][$key] = $item;
}

ksort($grouped_array, SORT_NUMERIC);


print_r($grouped_array);




/*
run:

Array
(
    [2] => Array
        (
            [c] => Array
                (
                    [id] => 2
                    [name] => ooo
                )

            [e] => Array
                (
                    [id] => 2
                    [name] => www
                )

        )

    [3] => Array
        (
            [b] => Array
                (
                    [id] => 3
                    [name] => qqq
                )

            [d] => Array
                (
                    [id] => 3
                    [name] => ppp
                )

        )

    [4] => Array
        (
            [a] => Array
                (
                    [id] => 4
                    [name] => vvv
                )

        )

    [5] => Array
        (
            [f] => Array
                (
                    [id] => 5
                    [name] => mmm
                )

            [g] => Array
                (
                    [id] => 5
                    [name] => zzz
                )

        )

)

*/

 



answered Dec 9, 2023 by avibootz

Related questions

1 answer 90 views
1 answer 143 views
1 answer 165 views
2 answers 188 views
1 answer 172 views
1 answer 96 views
...