繁体   English   中英

两个如何比较php中的两个JSON对象数组?

[英]How two compare two JSON objects array in php?

我有如下所示的 JSON 对象数组。 以下 JSON 对象数组位于文件(process/ptp-hello.json) 中

{
    "list": ["1", "2"],
    "code": ["ABCD", "DEFG", "PQRT", "KJHG", "OOPO", "MNBG", "IUYT"]
}

代码:

<?php
if (file_exists('process/ptp-hello.json')) {
    $letter = json_decode(file_get_contents('process/ptp-hello.json'));  // Line A
}
?>

<?php foreach ($letter->list as $key => $value) { ?>
    <a href="/en/?s=&port=<?php echo $letter->code[$value]; ?>">
        <div class="beats">
            <div class="color-green"><?php echo $letter->code[$value]; ?></div>    // Line B 
        </div>
    </a>
<?php }

B 行打印DEFGPQRT

问题陈述:

我想知道我应该在上面的 php 代码中进行哪些更改,以便它打印 ABCD、KJHG、OOPO、MNBG 和 IUYT。

简而言之,我想从code删除那些索引列在list元素

您可以像这样过滤代码:

$remainingCodes = array_diff_key($data_house->code, array_flip($data_house->joint_committees));

var_dump($remainingCodes);
// array(5) { [0]=> string(4) "CACN" [3]=> string(4) "CIMM" [4]=> string(4) "ENVI" [5]=> string(4) "ETHI" [6]=> string(4) "FAAE" }

然后您可以遍历$remainingCodes变量。

这是它的工作原理:

  1. 使用array_flip翻转$data_house->joint_committees数组的键和值
  2. array_diff_key去掉最后一个数组的值对应的$data_house->code的key

有很多方法可以实现这一点,下面列出了三种:

1. 迭代code但如果joint_committees存在key则不打印任何joint_committees

<?php foreach ($data_house->code as $key => $value) {
    if (!in_array($key, $data_house->joint_committees) { ?>
        <!-- Your HTML here -->
    <?php }
}

注意:这也可以通过if (!in_array($key, $data_house->joint_committees) continue;而不将 HTML 放入条件中。

2.首先循环joint_committees并从code删除任何匹配项

<?php
for ($data_house->joint_committees as $index) {
    $data_house->code = array_splice($data_house, $index, 1);
}

foreach ($data_house->code as $value) { ?>
    <!-- Your HTML here -->
<?php }

注意:您也可以使用unset($data_house->code[$index])但它会留下一个带有非连续索引的“奇怪”数组。

3.将code映射到没有joint_committees索引的数组

<?php
$filteredCodes = array_filter($data_house->code, function ($key) use ($data_house) {
    return !in_array($key, $data_house->joint_committees)
}, ARRAY_FILTER_USE_KEY);

foreach ($filteredCodes as $value) { ?>
    <!-- Your HTML here -->
<?php }

注意:从 PHP 7.4 开始, array_filter调用可以简化为:

$filteredCodes = array_filter($data_house->code, fn($key) => !in_array($key, $data_house->joint_committees), ARRAY_FILTER_USE_KEY);

更新: Brewal在他们的回答中提出了另一个可能更优雅的解决方案。 :-)

应该很简单

$json = '{
"joint_committees": ["1", "2"],
"code": ["CACN", "CHPC", "CIIT", "CIMM", "ENVI", "ETHI", "FAAE"]
}';

$data_house = json_decode($json, true);


foreach($data_house['code'] as $key => $val) {
    if(!in_array($key, $data_house['joint_committees'])) {
        echo $key . ' ' . $val ."\n";
    }
}

这返回

0 CACN
3 CIMM
4 ENVI
5 ETHI
6 FAAE

您可以对返回值做很多事情,创建一个新数组,回显信息,无论您想做什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM