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

CodeIgniter3中比对两个JSON数组筛选available为1的对应数据

CodeIgniter3 双JSON数组筛选实现方案

前置准备

先将两个JSON字符串转换为PHP关联数组,后续基于数组做匹配逻辑:

// 待筛选的源JSON,实际场景可从接口、数据库或请求参数中获取
$sourceJson = '
[
    {"id":23456,"name":"Some data"},
    {"id":98765,"name":"Other data"},
    {"id":12345,"name":"A glider"},
    {"id":34567,"name":"Other aircraft"}
]';
// 带available标记的对比JSON
$compareJson = '
[
    {"id":23456,"name":"Some data","available": 0},
    {"id":98765,"name":"Other data","available": 1},
    {"id":12345,"name":"A glider","available": 0},
    {"id":34567,"name":"Other aircraft","available": 0},
    {"id":56789,"name":"Dummy aircraft","available": 0}
]';

// 转换为关联数组,json_decode第二个参数传true返回数组而非对象
$sourceArr = json_decode($sourceJson, true);
$compareArr = json_decode($compareJson, true);

步骤1:构造ID映射表(提升查找效率)

先把对比数组处理为以ID为键的映射,避免筛选时循环遍历整个对比数组,优化性能:

$availableMap = [];
foreach ($compareArr as $item) {
    $availableMap[$item['id']] = $item['available'];
}

步骤2:执行筛选逻辑

遍历源数组,匹配两个条件:ID在对比数组中存在、对应available值为1:

$result = [];
foreach ($sourceArr as $item) {
    if (isset($availableMap[$item['id']]) && $availableMap[$item['id']] === 1) {
        $result[] = $item;
    }
}

筛选结果

你给出的示例中最终输出的$result内容如下:

[
    {
        "id":98765,
        "name":"Other data"
    }
]

CodeIgniter3 适配提示

如果JSON来自请求参数,可直接用CI的输入类获取,自带XSS过滤更安全:

$sourceJson = $this->input->post('source_json', true);
$compareJson = $this->input->post('compare_json', true);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:45:04