I want to merge two arrays but with 2 constraints:
first array :
{
"products": {
"0": {
"title": "myTitle",
"url": "xxxxxx",
"id": "309132"
},
"1": {
"title": "myTitle",
"url": "",
"id": "309123",
},...
}
}
second array :
{
"products": {
"0": {
"title": "myTitle",
"url": "xxxxxx",
"id": "329102"
},
"1": {
"title": "myTitle",
"url": "",
"id": "439023",
},...
}
}
I tried :
$data3 = array_unique(array_merge($data1,$data2), SORT_NUMERIC);
or with SORT_REGULAR
, but I did not achieve my requirements.
Your data does not look like an array it is JSON. using same structure of your json in array, you can try this:
<?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);