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

查看:396
本文介绍了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?

对不起,我忘了,IDS永远比不上对方,但在技术上可能的名字,但不会是有可能的,他们都需要在一个阵列中列出。我看着array_merge,但不知道这是否是要做到这一点最好的办法。此外,你会如何单元测试吗?

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 () 是更有效,但也有几个选项:

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>';

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

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