Group Subarrays by Column, Create Comma-Separated Values for Different Columns in Groups in PHP
To group subarrays based on a specific column and generate comma-separated values from a different column within each group, you can utilize the following approach:
Traverse the Input Array:
<code class="php">$data = [ ["444", "0081"], ["449", "0081"], ["451", "0081"], ["455", "2100"], ["469", "2100"] ];</code>
Initialize Empty Arrays:
<code class="php">$groups = []; $structured = [];</code>
Group Subarrays by Second Column:
Iterate through the $data array and group subarrays based on the second column value:
<code class="php">foreach ($data as $item) { $groups[$item[1]][] = $item[0]; }</code>
Structure the Output Array:
Create the output array in the desired format:
<code class="php">foreach ($groups as $key => $values) { $structured[] = [implode(',', $values), $key]; }</code>
The $structured array will now contain the grouped subarrays with comma-separated values for the first column in each group:
<code class="php">array ( 0 => array ( 0 => '444,449,451', 1 => '0081', ), 1 => array ( 0 => '455,469', 1 => '2100', ), )</code>
The above is the detailed content of How to Group Subarrays by Column and Generate Comma-Separated Values in PHP?. For more information, please follow other related articles on the PHP Chinese website!