dongyu4554 2012-11-01 02:45
浏览 180
已采纳

PHP将两个关联数组合并为一个数组

$array1 = array("$name1" => "$id1");

$array2 = array("$name2" => "$id2", "$name3" => "$id3");

I need a new array combining all together, i.e. it would be

$array3 = array("$name1" => "$id1", "$name2" => "$id2", "$name3" => "$id3");

What is the best way to do this?

Sorry, I forgot, the ids will never match each other, but technically the names could, yet would not be likely, and they all need to be listed in one array. I looked at array_merge but wasn't sure if that was best way to do this. Also, how would you unit test this?

  • 写回答

7条回答 默认 最新

  • doushan1157 2012-11-01 02:50
    关注

    array_merge() is more efficient but there are a couple of options:

    $array1 = array("id1" => "value1");
    
    $array2 = array("id2" => "value2", "id3" => "value3", "id4" => "value4");
    
    $array3 = array_merge($array1, $array2/*, $arrayN, $arrayN*/);
    $array4 = $array1 + $array2;
    
    echo '<pre>';
    var_dump($array3);
    var_dump($array4);
    echo '</pre>';
    
    
    // Results:
        array(4) {
          ["id1"]=>
          string(6) "value1"
          ["id2"]=>
          string(6) "value2"
          ["id3"]=>
          string(6) "value3"
          ["id4"]=>
          string(6) "value4"
        }
        array(4) {
          ["id1"]=>
          string(6) "value1"
          ["id2"]=>
          string(6) "value2"
          ["id3"]=>
          string(6) "value3"
          ["id4"]=>
          string(6) "value4"
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?