Organizing Associative Array Rows by Column Value
When working with an associative array consisting of subarrays, it is often necessary to reorganize the data based on specific column values. This allows for easier data retrieval and analysis.
Suppose we have an array of subarrays in the following format:
[ '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'] ]
Our goal is to group these subarrays into a new array based on the 'id' field present in each subarray.
To achieve this, we can follow these steps:
$arr = array();
foreach ($old_arr as $key => $item) { $arr[$item['id']][$key] = $item; }
ksort($arr, SORT_NUMERIC);
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 ) ) )
The above is the detailed content of How to Organize Associative Array Rows Based on a Specific Column Value?. For more information, please follow other related articles on the PHP Chinese website!