Home  >  Article  >  Backend Development  >  How to Group Subarrays and Format Values by Column in PHP?

How to Group Subarrays and Format Values by Column in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 09:45:02721browse

How to Group Subarrays and Format Values by Column in PHP?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn