Home > Backend Development > PHP Tutorial > How to Group Array Elements and Combine Values from Another Column in a Multidimensional Array?

How to Group Array Elements and Combine Values from Another Column in a Multidimensional Array?

Linda Hamilton
Release: 2024-11-02 12:20:30
Original
569 people have browsed it

How to Group Array Elements and Combine Values from Another Column in a Multidimensional Array?

Grouping Array Elements by Column and Combining Values from Another Column

Given an array containing nested arrays with two columns, the task is to group the subarrays based on a specific column and concatenate the values from another column within each group, resulting in a comma-separated list.

Consider the following example array:

<code class="php">$array = [
    ["444", "0081"],
    ["449", "0081"],
    ["451", "0081"],
    ["455", "2100"],
    ["469", "2100"]
];</code>
Copy after login

The desired result is:

<code class="php">[
  ["444,449,451", "0081"],
  ["455,469", "2100"]
]</code>
Copy after login

One solution to this problem involves the following steps:

  1. Iterate through the given array, and for each item:

    • Check if the group (represented by the second column value) exists in the new array.
    • If not, create a new group in the new array with that group.
    • Add the first column value (the ID) to the corresponding group.
  2. Once all items have been processed, the new array will contain groups with lists of IDs.
  3. Finally, restructure the array to match the required format by creating new subarrays for each group with the first column concatenated and the second column as is.

The above is the detailed content of How to Group Array Elements and Combine Values from Another Column in a Multidimensional Array?. 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