合并两个数组:按id排序并删除重复 - PHP

时间:2017-01-10 10:13:15

标签: php arrays merge

我想合并两个数组但有两个约束:

  • 根据ID
  • 按顺序排序
  • 如果有两个相同的ID,则只显示一次(无重复)

第一个数组:

{
    "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,但我没有达到我的要求。

1 个答案:

答案 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);

DEMO HERE

相关问题