Merge arrays (PHP)

后端 未结 2 495
无人共我
无人共我 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 ,).

    0 讨论(0)
  • 2020-12-20 09:26

    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

    0 讨论(0)
提交回复
热议问题