How to Group Subarrays by Column and Generate Comma-Separated Values in PHP?

Mary-Kate Olsen
Release: 2024-11-04 13:19:01
Original
262 people have browsed it

How to Group Subarrays by Column and Generate Comma-Separated Values in PHP?

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:

  1. Traverse the Input Array:

    <code class="php">$data = [
        ["444", "0081"],
        ["449", "0081"],
        ["451", "0081"],
        ["455", "2100"],
        ["469", "2100"]
    ];</code>
    Copy after login
  2. Initialize Empty Arrays:

    <code class="php">$groups = [];
    $structured = [];</code>
    Copy after login
  3. 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>
    Copy after login
  4. 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>
    Copy after login

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!