如何在PHP中比较两个JSON文件

时间:2018-09-28 13:10:41

标签: php json

我正在处理JSON文件以比较它们的数据。我只想显示相同的数据,但是我想比较两个整个文件。 这是我正在使用的代码:

<?php 
$data = file_get_contents("json/categories.json");
$data1 = file_get_contents("json/categories.json");
$data = json_decode($data, true);
$data1 = json_decode($data1, true);
$result_array = array_diff($data, $data1);
echo "you got it";

/*
foreach ($data1 as $v) {
    foreach ($data as $m) {
        if ($v['LocationCategoryNo'] == $m['LocationCategoryNo']) {
            echo $m[LocationCategoryNo'] . " " . $m['LocationCategoryNo'];
        }
    }
}
*/

$found = array_search($data1, array_column($data, 'LocationCategoryNo'));
if ($found === False) {
    echo "Not Found";
} else {
    echo $data[$found]['LocationCategoryNo'];
}
//$common_items = array_intersect($data, $data1);
?>

1 个答案:

答案 0 :(得分:0)

<?php

$json1 = <<<END
[
    {"LocationCategoryNo":1},
    {"LocationCategoryNo":2},
    {"LocationCategoryNo":3},
    {"LocationCategoryNo":4},
    {"LocationCategoryNo":5}
]
END;


$json2 = <<<END
[
    {"LocationCategoryNo":4},
    {"LocationCategoryNo":5},
    {"LocationCategoryNo":6},
    {"LocationCategoryNo":7},
    {"LocationCategoryNo":8}
]
END;


$data1 = json_decode($json1, true);
$data2 = json_decode($json2, true);

//If you want the full records matched by the value of LocationCategoryNo
$commonRecords = array_filter($data1, function($currTuple)
{
    global $data2;

    foreach($data2 as $currCompareTuple)
    {
        if($currCompareTuple['LocationCategoryNo'] == $currTuple['LocationCategoryNo'])
        {
            return true;
        }
    }

    return false;
});


//If you just want the matching LocationCategoryNo values
$ids1 = array_column($data1,'LocationCategoryNo');
$ids2 = array_column($data2,'LocationCategoryNo');

$commonIds = array_intersect($ids1, $ids2);