我想要两个合并两个数组和一个自定义顺序:从数组1中获取一个值,然后从数组2中获取一个值,如下所示:
$array1 = array('key1' => 'value_1_1', 'key2' => 'value_1_2');
$array2 = array('key1' => 'value_2_1', 'key2' => 'value_2_2');
//merge array with custom order
$array_result = array('key1' => array('value_1_1', 'value_2_1'),
'key2' => array('value_2_1', 'value_2_2')
)
值不同,两个数组上的键都相同。
答案 0 :(得分:2)
内置功能
$result = array_merge_recursive($array1, $array2);
答案 1 :(得分:0)
$result = array();
foreach(array_keys($array1 + $array2) as $key)
{
if(array_key_exists($key, $array1) && array_key_exists($key, $array2))
$result[$key] = array($array1[$key], $array2[$key]);
else
$result[$key] = array_key_exists($key, $array1) ? $array1[$key] : $array2[$key];
}
答案 2 :(得分:-1)
试试这个:
$array1 = array('key1' => 'value_1_1', 'key2' => 'value_1_2');
$array2 = array('key1' => 'value_2_1', 'key2' => 'value_2_2');
$result = array();
/* Create index for $result */
foreach($array1 as $data => $value) {
$result[$data] = array();
}
/* Craete Value for $result from array 1*/
foreach($array1 as $data => $value) {
array_push($result[$data], $value);
}
/* Craete Value for $result from array 2*/
foreach($array2 as $data => $value) {
array_push($result[$data], $value);
}