Home > Article > Backend Development > How to Group Associative Array Rows by Column Value in PHP?
Grouping Associative ArrayRows by Column Value
In programming, you may encounter situations where you need to reorganize data stored in associative arrays. One common task is to group rows in the array by a specific column value while preserving the original first-level keys.
Consider the following associative array of associative arrays known as $old_arr:
[ 'a' => ['id' => 20, 'name' => 'chimpanzee'], 'b' => ['id' => 40, 'name' => 'meeting'], 'c' => ['id' => 20, 'name' => 'dynasty'], 'd' => ['id' => 50, 'name' => 'chocolate'], 'e' => ['id' => 10, 'name' => 'bananas'], 'f' => ['id' => 50, 'name' => 'fantasy'], 'g' => ['id' => 50, 'name' => 'football'] ]
The goal is to create a new array, $arr, where rows are grouped based on the id field. The resulting array should look like this:
array ( 10 => array ( e => array ( id = 10, name = bananas ) ) 20 => array ( a => array ( id = 20, name = chimpanzee ) c => array ( id = 20, name = dynasty ) ) 40 => array ( b => array ( id = 40, name = meeting ) ) 50 => array ( d => array ( id = 50, name = chocolate ) f => array ( id = 50, name = fantasy ) g => array ( id = 50, name = football ) ) )
To achieve this, you can follow these steps:
The provided PHP code follows this approach to generate the desired result:
$arr = array(); foreach ($old_arr as $key => $item) { $arr[$item['id']][$key] = $item; } ksort($arr, SORT_NUMERIC);
The above is the detailed content of How to Group Associative Array Rows by Column Value in PHP?. For more information, please follow other related articles on the PHP Chinese website!