"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-06
Browse:248

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:

$array = [
    ["444", "0081"],
    ["449", "0081"],
    ["451", "0081"],
    ["455", "2100"],
    ["469", "2100"]
];

The desired result is:

[
  ["444,449,451", "0081"],
  ["455,469", "2100"]
]

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.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3