Vadim
Vadim

Reputation: 27

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],
]

Upvotes: 0

Views: 786

Answers (2)

Mark Baker
Mark Baker

Reputation: 212522

Simply building slightly on user576875's method:

$a = array ( 0 => array ( 'id' => 3,
                          'title' => 'book',
                          'tval' => 10000
                        ),
            1 => array  ( 'id' => 3,
                          'title' => 'book',
                          'tval' => 1700
                        ),
            3 => array  ( 'id' => 27,
                          'bcalias' => 'fruit',
                          'tval' => 3000
                        )
          );

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

var_dump($result);

gives a result of:

array
  0 => 
    array
      'id' => int 3
      'title' => string 'book' (length=4)
      'tval' => string '10000,1700' (length=10)
  1 => 
    array
      'id' => int 27
      'bcalias' => string 'fruit' (length=5)
      'tval' => int 3000

The only real difference is the array_merge() to reset the keys

Upvotes: 0

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99919

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 ,).

Upvotes: 3

Related Questions