
本文介绍如何在 php 中对已解码的 json 数组进行条件筛选,模拟 sql 的 where 行为,使用 `array_filter()` 配合匿名函数高效匹配指定字段(如 `invoice_number`),并返回符合要求的 json 子集。
在实际开发中,我们常需对前端传入的 ID(如发票号)在本地解析后的 JSON 数据中进行精确查找——这类似于数据库中的 WHERE invoice_number = ? 查询。但 JSON 解析后是 PHP 关联数组或对象,无法直接使用 SQL 语法,必须借助数组处理函数实现等效逻辑。
核心方案是使用 array_filter() 对 $decoded_result['invoices'](假设为发票数组)进行遍历过滤。注意:务必先校验输入、避免变量覆盖,并确保 JSON 已正确解码为关联数组(即 json_decode($json, true))。以下是 C.php 的优化实现:
<?php
header('Content-Type: application/json; charset=utf-8');
if (isset($_POST['_zid']) && is_string($_POST['_zid'])) {
$targetId = trim($_POST['_zid']);
// 确保 $decoded_result 已在全局作用域中正确定义且包含 'invoices' 键
global $decoded_result;
if (!isset($decoded_result['invoices']) || !is_array($decoded_result['invoices'])) {
http_response_code(400);
echo json_encode([]);
exit;
}
// 使用 array_filter 筛选 invoice_number 匹配的项(模拟 WHERE)
$filtered = array_filter($decoded_result['invoices'], function ($item) use ($targetId) {
return isset($item['invoice_number']) && $item['invoice_number'] === $targetId;
});
// 重置数组键以确保 JSON 输出为标准索引数组(避免关联键导致 JS 解析为对象)
$resultArray = array_values($filtered);
echo json_encode($resultArray);
} else {
http_response_code(400);
echo json_encode([]);
}
?>⚠️ 关键注意事项:
- 安全性:始终校验 $_POST['_zid'] 是否存在、是否为字符串、是否为空,防止空值或非法类型引发错误;
- 变量作用域:global $decoded_result 仅在函数内有效;若 C.php 未包含 A.php,需确保 $decoded_result 已提前加载并可访问(推荐通过 require_once 'A.php'; 显式引入);
- 键名一致性:示例中匹配的是 'invoice_number' 字段,若实际 JSON 中 ID 字段名为 'id' 或 'zid',请同步修改回调函数中的键名;
- JSON 响应头:添加 header('Content-Type: application/json'),确保前端 dataType: 'json' 能正确解析;
- 前端健壮性:AJAX 成功回调中应检查 data.length > 0,避免 data[0] 访问空数组报错。
该方法简洁高效,无需循环手动 push,也规避了 foreach 中 break 的复杂控制,是处理中小型 JSON 数据集条件查询的最佳实践。
立即学习“PHP免费学习笔记(深入)”;











