How can I merge PHP arrays?

前端 未结 10 1822
盖世英雄少女心
盖世英雄少女心 2020-12-20 12:43

I have two arrays of animals (for example).

$array = array(
    array(
        \'id\' => 1,
        \'name\' => \'Cat\',
    ),
    array(
        \'id         


        
10条回答
  •  天涯浪人
    2020-12-20 13:12

    First off, why don't you use the ID as the index (or key, in the mapping-style array that php arrays are imo)?

    $array = array(
        1 => array(
            'name' => 'Cat',
        ),
        2 => array(
            'name' => 'Mouse',
        )
    );
    

    after that you'll have to foreach through one array, performing array_merge on the items of the other:

    foreach($array2 as $key=>$value) {
      if(!is_array($array[$key])) $array[$key] = $value;
      else $array[$key] = array_merge($array[key], $value); 
    }
    

    Something like that at least. Perhaps there's a better solution?

提交回复
热议问题