Group Subarrays by Column, Format Values from Other Column Within Groups
In a given array where each subarray consists of two columns, the task is to group the subarrays by the second column and create a new array where each group has the values from the first column concatenated with commas and the second column as the second value.
For example, an input array like:
$array = [ ["444", "0081"], ["449", "0081"], ["451", "0081"], ["455", "2100"], ["469", "2100"] ];
should be transformed into:
array ( 0 => array ( 0 => '444,449,451', 1 => '0081', ), 1 => array ( 0 => '455,469', 1 => '2100', ), )
Solution:
A straightforward approach to achieve this is as follows:
<code class="php">// Create an empty array to store the grouped data $groups = []; // Loop through the input array foreach ($array as $item) { // If the second column value is not yet a key in $groups, create an empty array for it if (!array_key_exists($item[1], $groups)) { $groups[$item[1]] = []; } // Add the first column value to the array at the corresponding key $groups[$item[1]][] = $item[0]; } // Initialize the new array with the desired structure $structured = []; // Loop through the groups foreach ($groups as $group => $values) { // Join the first column values with commas and add the group key as the second column $structured[] = [implode(',', $values), $group]; }</code>
This solution handles the transformation efficiently, resulting in the desired output.
The above is the detailed content of How to Group Subarrays and Format Values by Column in PHP?. For more information, please follow other related articles on the PHP Chinese website!