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

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

Linda Hamilton
Release: 2024-11-02 09:45:02
Original
831 people have browsed it

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"]
];
Copy after login

should be transformed into:

array (
  0 => 
  array (
    0 => '444,449,451',
    1 => '0081',
  ),
  1 => 
  array (
    0 => '455,469',
    1 => '2100',
  ),
)
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template