Home > Backend Development > PHP Tutorial > How to Group Subarrays by One Column and Generate Comma-Separated Values from Another Column?

How to Group Subarrays by One Column and Generate Comma-Separated Values from Another Column?

DDD
Release: 2024-11-02 18:11:02
Original
650 people have browsed it

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

Desired Structure:

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template