You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现两个JSON数组对比并补全缺失元素(带默认值)

解决方案

要实现为数组b补充数组a中缺失的id元素并设置默认count值,不能直接用array_merge(它仅做简单数组合并,不会对比id补全缺失项),可以按以下逻辑处理:

实现代码

<?php
$a = '[{"id":1,"name":"test1"},{"id":"2","name":"test1"},{"id":"3","name":"test1"}]';
$b = '[{"id":2,"count":10},{"id":"3","count":11},{"id":"4","count":13}]';

// 解码JSON为PHP关联数组
$arrayA = json_decode($a, true);
$arrayB = json_decode($b, true);

// 提取数组a中所有id,统一转为字符串避免类型匹配问题
$idsInA = array_map(function($item) {
    return (string)$item['id'];
}, $arrayA);

// 提取数组b中已有的id,同时建立id到元素的映射
$existingIdsInB = [];
foreach ($arrayB as $item) {
    $existingIdsInB[] = (string)$item['id'];
}

// 生成数组b缺失的元素(count默认设为0)
$missingItems = [];
foreach ($arrayA as $itemA) {
    $idStr = (string)$itemA['id'];
    if (!in_array($idStr, $existingIdsInB)) {
        $missingItems[] = [
            'id' => $itemA['id'],
            'count' => 0
        ];
    }
}

// 合并缺失元素与原数组b,再按id排序贴合示例输出顺序
$newArrayB = array_merge($missingItems, $arrayB);
usort($newArrayB, function($x, $y) {
    return (int)$x['id'] - (int)$y['id'];
});

// 输出最终结果
echo "a=" . json_encode($arrayA) . ";\n";
echo "b=" . json_encode($newArrayB) . ";\n";
?>

代码说明

  1. 先将JSON字符串解码为PHP关联数组,方便后续操作
  2. 统一把id转为字符串做匹配,避免数字与字符串类型不一致导致的匹配失败(比如1和"1")
  3. 遍历数组a的id,对比数组b已有的id,生成缺失的默认元素(count固定为0)
  4. 合并后对数组b按id排序,保证输出顺序和示例一致
  5. 最后重新编码为JSON字符串,得到目标结果

内容的提问来源于stack exchange,提问作者user1738638

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:55:18