Home >Backend Development >PHP Tutorial >How to Group Subarrays by One Column and Generate Comma-Separated Values from Another Column?
Grouping Subarrays by One Column and Generating Comma-Separated Values from Other Column
Introduction
Given an array of subarrays with two columns, the task is to group these subarrays by one column and create new subarrays where the values in the other column are comma-separated.
Original Structure:
$array = [ ["444", "0081"], ["449", "0081"], ["451", "0081"], ["455", "2100"], ["469", "2100"] ];
Desired Structure:
array ( 0 => array ( 0 => '444,449,451', 1 => '0081', ), 1 => array ( 0 => '455,469', 1 => '2100', ), )
Solution
An elegant solution can be achieved by iterating through the original array and collecting values into a temporary array based on the grouping key. Subsequently, the temporary array is used to construct the desired structure.
<code class="php">$data = []; $groups = []; foreach($data as $item){ if(!array_key_exists($item[1], $groups)){ $groups[$item[1]] = []; } $groups[$item[1]][] = $item[0]; } $structured = []; foreach($groups as $group => $values){ $structured[] = [implode(',', $values), $group]; }</code>
This approach ensures that subarrays are grouped correctly and the values in the other column are combined as comma-separated strings. It utilizes basic PHP array functions and foreach loops to achieve the desired outcome.
The above is the detailed content of How to Group Subarrays by One Column and Generate Comma-Separated Values from Another Column?. For more information, please follow other related articles on the PHP Chinese website!