我有两种 json 格式,我正在将 json 转换为数组然后合并它,但它不起作用。
看下面两种json格式。
下面是我的 PHP 代码,它没有合并数组,这里有什么问题?
$arr1 = json_decode('{
"PatchDeployment":[
{
"ehubid":"123",
"tomcats":[
{
"tomcatname":"mytomcat",
"servername":"myserver",
"serverip":"xx.xx.xx.xxx",
"tomcat_statuses":{
"stoptomcat":"Success"
}
}
]
}
]
}', true);
$arr2 = json_decode('{
"PatchDeployment":[
{
"ehubid":"123",
"tomcats":[
{
"tomcatname":"mytomcat",
"servername":"myserver",
"serverip":"xx.xx.xx.xxx",
"tomcat_statuses":{
"checkdb":"Failed",
"checkhub":"couldnt connect to host"
}
}
]
}
]
}', true);
$mergedarray = array_merge($arr1, $arr2);
我希望数组在合并 $mergedarray 后应该像下面这样:
Array
(
[PatchDeployment] => Array
(
[0] => Array
(
[ehubid] => 123
[tomcats] => Array
(
[0] => Array
(
[tomcatname] => mytomcat
[servername] => myserver
[serverip] => xx.xx.xx.xxx
[tomcat_statuses] => Array
(
[checkdb] => Failed
[checkhub] => couldnt connect to host
[stoptomcat]=> Success
)
)
)
)
)
)
我正在将两个数组合并到 php
谁能帮我尽快解决这个问题?
尝试使用
array_merge_recursive
:
$mergedArr = array_merge_recursive($arr1, $arr2);
你不希望他们重复。您要找的方法:
array_replace_recursive
$arr1 = json_decode('{
"PatchDeployment":[
{
"ehubid":"123",
"tomcats":[
{
"tomcatname":"mytomcat",
"servername":"myserver",
"serverip":"xx.xx.xx.xxx",
"tomcat_statuses":{
"stoptomcat":"Success"
}
}
]
}
]
}', true);
$arr2 = json_decode('{
"PatchDeployment":[
{
"ehubid":"123",
"tomcats":[
{
"tomcatname":"mytomcat",
"servername":"myserver",
"serverip":"xx.xx.xx.xxx",
"tomcat_statuses":{
"checkdb":"Failed",
"checkhub":"couldnt connect to host"
}
}
]
}
]
}', true);
$mergedarray = array_replace_recursive($arr1, $arr2);
print '<pre>';
print_r($mergedarray);
print '</pre>';
exit;
结果
Array
(
[PatchDeployment] => Array
(
[0] => Array
(
[ehubid] => 123
[tomcats] => Array
(
[0] => Array
(
[tomcatname] => mytomcat
[servername] => myserver
[serverip] => xx.xx.xx.xxx
[tomcat_statuses] => Array
(
[stoptomcat] => Success
[checkdb] => Failed
[checkhub] => couldnt connect to host
)
)
)
)
)
)