我想合并两个数组但有两个约束:
第一个数组:
{
"products": {
"0": {
"title": "myTitle",
"url": "xxxxxx",
"id": "309132"
},
"1": {
"title": "myTitle",
"url": "",
"id": "309123",
},...
}
}
第二个数组:
{
"products": {
"0": {
"title": "myTitle",
"url": "xxxxxx",
"id": "329102"
},
"1": {
"title": "myTitle",
"url": "",
"id": "439023",
},...
}
}
我试过了:
$data3 = array_unique(array_merge($data1,$data2), SORT_NUMERIC);
或SORT_REGULAR
,但我没有达到我的要求。
答案 0 :(得分:0)
您的数据看起来不像是JSON的数组。 在数组中使用相同的json结构,你可以试试这个:
<?php
$arr=array(
"products"=> array(
"0"=> array(
"title"=> "myTitle",
"url"=> "xxxxxx",
"id"=> "309132"
),
"1"=> array(
"title"=> "myTitle",
"url"=> "",
"id"=> "309123",
)
)
);
//similar $arr1['products']
function cmp($a, $b)
{
if ($a["id"] == $b["id"]) {
return 0;
}
return ($a["id"] < $b["id"]) ? -1 : 1;//sorts in decending order by ratings..
}
$array['products']=array_merge($arr['products'],$arr1['products']);
usort($array['products'],"cmp");
$array['products'] = array_values(array_map("unserialize", array_unique(array_map("serialize", $array['products']))));
echo '<pre>';
print_r($array);