Merge arrays (PHP)

后端 未结 2 496
无人共我
无人共我 2020-12-20 09:12

How combine arrays in this way?

source:

Array
(
   [0] => Array
       (
           [id] => 3
           [title] => book
           [tval] =         


        
2条回答
  •  不知归路
    2020-12-20 09:16

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

提交回复
热议问题