PHP 将两个关联数组合并为一个数组 [英] PHP combine two associative arrays into one array

查看:103
本文介绍了PHP 将两个关联数组合并为一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我需要一个组合在一起的新数组,即

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

最好的方法是什么?

抱歉,我忘记了,id 永远不会相互匹配,但从技术上讲,名称可以,但不太可能,而且它们都需要列在一个数组中.我查看了 array_merge,但不确定这是否是最好的方法.另外,您将如何对其进行单元测试?

解决方案

array_merge() 效率更高,但有几个选项:

$array1 = array("id1" => "value1");$array2 = array("id2" => "value2", "id3" => "value3", "id4" => "value4");$array3 = array_merge($array1, $array2/*, $arrayN, $arrayN*/);$array4 = $array1 + $array2;echo '

';var_dump($array3);var_dump($array4);echo '</pre>';//结果:数组(4){[id1"]=>字符串(6)值1"[id2"]=>字符串(6)值2"[id3"]=>字符串(6)值3"[id4"]=>字符串(6)值4"}数组(4){[id1"]=>字符串(6)值1"[id2"]=>字符串(6)值2"[id3"]=>字符串(6)值3"[id4"]=>字符串(6)值4"}

$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?

解决方案

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"
    }

这篇关于PHP 将两个关联数组合并为一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆