PHP比较两个数组键并组合成一个新数组(格式错误)

时间:2017-07-24 16:26:17

标签: php arrays

我有两个数组,想要比较 array_1和array_2 的相同键,并将它们组合成一个新的数组,如 array_3

编码

$array_1['value1']="";
$array_1['value2']="";
$array_1['value3']="";
$array_1['value4']="";
$array_1['value5']="";

$array_2['value1']="5";
$array_2['value3']="10";
$array_2['value5']="15";

/*
I want the format to be like this after merging.

$array_3['value1']="5";
$array_3['value2']="";
$array_3['value3']="10";
$array_3['value4']="";
$array_3['value5']="15";

*/

$results=array_merge_recursive($array_1,$array_2);
echo '<pre>',print_r($results),'</pre>';

enter image description here 通过使用 array_merge_recursive ,数组格式不是我想要的。任何人都知道如何获得截图右侧的结果格式?

1 个答案:

答案 0 :(得分:1)

普通array_merge应该可以解决问题:

<?php

$array_1['value1']="";
$array_1['value2']="";
$array_1['value3']="";
$array_1['value4']="";
$array_1['value5']="";

$array_2['value1']="5";
$array_2['value3']="10";
$array_2['value5']="15";

/*
I want the format to be like this after merging.

$array_3['value1']="5";
$array_3['value2']="";
$array_3['value3']="10";
$array_3['value4']="";
$array_3['value5']="15";

*/

$results=array_merge($array_1,$array_2);
echo print_r($results);

结果:

Array
(
    [value1] => 5
    [value2] => 
    [value3] => 10
    [value4] => 
    [value5] => 15
)
1