phparraysmultidimensional-arrayconcatenationgrouping

Group 2d array rows by one column and build a comma-separated string from another column's values within each group


How can I consolidate the rows in my 2d array by groing on id values and making a comma-separated string from the tval values?

Input array:

[
    ['id' => 3, 'title' => 'book', 'tval' => 10000],
    ['id' => 3, 'title' => 'book', 'tval' => 1700],
    3 => ['id' => 27, 'title' => 'fruit', 'tval' => 3000],
]

Desired result:

[
    ['id' => 3, 'title' => 'book', 'tval' => '10000,1700'],
    3 => ['id' => 27, 'title' => 'fruit', 'tval' => 3000],
]

Solution

  • This should work:

    $result = array();
    foreach($array as $elem) {
        $key = $elem['id'];
        if (isset($result[$key])) {
            $result[$key]['tval'] .= ',' . $elem['tval'];
        } else {
            $result[$key] = $elem;
        }
    }
    

    This basically groups elements by id, concatenating tvals (separated by ,).