如何比较2 json以查找具有深度的新条目?

时间:2018-10-12 05:58:59

标签: php arrays json compare

我想比较2个json,如果有新数组,它将获取新数组并将其插入数据库。

这是旧的json,

[{"menu_id":"1","menu_name":"Rapat 2018","parent_id":"0","link":"informent.online","status":"1"},
{"menu_id":"3","menu_name":"Rapat 2019","parent_id":"0","link":"#","status":"1"}]

这是新的json

[{"menu_id":"1","menu_name":"Rapat 2018","parent_id":"0","link":"informent.online","status":"1","children":[{"menu_id":"","menu_name":"Rapat RW","parent_id":"1","link":"#","status":"1"}]},
{"menu_id":"3","menu_name":"Rapat 2019","parent_id":"0","link":"#","status":"1"}]

有一个新的子数组(menu_name:Rapat RW),我想获得这个新数组,以便可以将其插入数据库。

这就是我所做的,

$json_str1 = '  [
                      {
                        "menu_id": "1",
                        "menu_name": "Rapat 2018",
                        "parent_id": "0",
                        "link": "informent.online",
                        "status": "1"
                      },
                      {
                        "menu_id": "3",
                        "menu_name": "Rapat 2019",
                        "parent_id": "0",
                        "link": "#",
                        "status": "1"
                      }
                    ]';
    $json_str2 = '  [
                      {
                        "menu_id": "1",
                        "menu_name": "Rapat 2018",
                        "parent_id": "0",
                        "link": "informent.online",
                        "status": "1",
                        "children": [
                          {
                            "menu_id": "",
                            "menu_name": "Rapat RW",
                            "parent_id": "1",
                            "link": "#",
                            "status": "1"
                          }
                        ]
                      },
                      {
                        "menu_id": "3",
                        "menu_name": "Rapat 2019",
                        "parent_id": "0",
                        "link": "#",
                        "status": "1"
                      }
                    ]';

    list($arr1, $arr2) = [json_decode($json_str1), json_decode($json_str2)];
    $common_items = array_intersect($arr2, $arr1);
    $result = array_filter(array_merge($arr1, $arr2), function($v) use($common_items){
        return !in_array($v, $common_items);
    });

    print_r($result);

但是我从“函数:array_intersect”中返回错误“类stdClass的对象无法转换为字符串” 问题是什么? 任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我看到array_intersect比较值作为字符串。从而使数组出现字符串错误。因为您的值中的一个是数组本身。要解决这个问题,您必须使用array_uintersect

http://php.net/array_uintersect

function myFunction($value1, $value2) {
    //compare and return 1 or 0
    return (int) $value1 !== $value2; //for example
}
$common_items = array_uintersect($arr2, $arr1, "myFunction");