PHP - 比较两个JSON对象的结构

Boa*_*ing 7 php json object

我有两个JSON对象,我想比较它们的结构.我该怎么做?

这些对象是在运行中生成的,具体取决于动态内容.这意味着对象总是不同的,但大多数时候具有相同的结构.我希望能够在发生变化时发现变化.

示例:这两个对象应该被视为相等,因为它们具有相同的结构:index var和tags数组.

{
    "index": 0,
    "tags": [
        "abc"
    ]
}
{
    "index": 1,
    "tags": [
        "xyz"
    ]
}
Run Code Online (Sandbox Code Playgroud)

思考?

Luc*_*iro 10

##你可以使用这个库TreeWalker php.##

TreeWalker是一个简单的小型API在PHP
(我开发了这个库,我希望它可以帮助你)

它提供了两种方法
1-获取json差异
2-编辑json值(递归)

这个方法将返回json1和json2之间的差异

$struct1 = array("casa"=>1, "b"=>"5", "cafeina"=>array("ss"=>"ddd"), "oi"=>5);
$struct2 = array("casa"=>2, "cafeina"=>array("ss"=>"dddd"), "oi2"=>5);

//P.s
print_r($treeWalker->getdiff($struct1, $struct2))

{
    new: {
        b: "5",
        oi: 5
    },
    removed: {
        oi2: 5
    },
    edited: {
        casa: {
          oldvalue: 2,
          newvalue: 1
        },
        cafeina/ss: {
          oldvalue: "dddd",
          newvalue: "ddd"
        }
    },
    time: 0
}
Run Code Online (Sandbox Code Playgroud)


von*_*sch 1

虽然有点粗糙,但你明白了;

$json = '[
        {
            "index": 0,
            "tags": [
                "abc"
            ]
        },
        {
            "index": 1,
            "tags": [
                "xyz"
            ]
        },
        {
            "foo": 2,
            "bar": [
                "xyz"
            ]
        }]';

$array = json_decode($json, true);
$default = array_keys($array[0]);

$error = false;
$errors = array();
foreach ($array as $index => $result):
    foreach ($default as $search):
        if (!isset($result[$search])):
            $error = true;
            $errors[] = "Property '{$search}' at entry '{$index}' not found. ";
        endif;
    endforeach;
endforeach;

if ($error):
    echo 'Objects are not the same. ';
    foreach ($errors as $message):
        echo $message;
    endforeach;
endif;
Run Code Online (Sandbox Code Playgroud)

返回:

对象并不相同。未找到条目“2”处的属性“索引”。未找到条目“2”处的属性“标签”。