Home  >  Article  >  Backend Development  >  How to Group Subarrays by Column and Generate Comma-Separated Values in PHP?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 13:19:01322browse

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>
  2. Initialize Empty Arrays:

    <code class="php">$groups = [];
    $structured = [];</code>
  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>
  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>

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!

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