我有两个数组,看起来像下面
$array1 = array("color" => "red","size" => "32");
$array2 = array("color" => "blue","width" => "40");
和我的PHP代码如下
<?php
$array1 = array("color" => "red","size" => "32");
$array2 = array("color" => "blue","width" => "40");
$result = array_merge_recursive($array1, $array2);
echo json_encode($result);
?>
该代码的输出是
{
color: [
"red",
"blue"
],
size: "32",
width: "40"
}
我想得到像
这样的输出{
color: [
"red",
"blue"
],
size: [
"32",
""
],
width: [
"",
"40"
]
}
我怎么能得到这个?请快点帮我。
使用默认值数组的array_merge
$array1 = array("color" => "red","size" => "32");
$array2 = array("color" => "blue","width" => "40");
$arrayInit = array("color" => "","width" => "","size"=>"");
$array1 = array_merge($arrayInit,$array1);
$array2 = array_merge($arrayInit,$array2);
$result = array_merge_recursive($array1, $array2);
echo json_encode($result);
$keys = array_keys(array_merge($array1, $array2)); // get all the keys
foreach ($keys as $key) {
// set each key in the result array to the value from the input array or a default ''
$result[$key][] = isset($array1[$key]) ? $array1[$key] : '';
$result[$key][] = isset($array2[$key]) ? $array2[$key] : '';
}
echo json_encode($result);