
本文详解如何在 PHP 中遍历 JSON 解析后的关联数组,根据条件(如 status === 2)筛选元素,并安全提取 swift_code 和 note 字段构建结构化新数组,同时处理缺失键(如 note 不存在时默认为空字符串)。
本文详解如何在 php 中遍历 json 解析后的关联数组,根据条件(如 `status === 2`)筛选元素,并安全提取 `swift_code` 和 `note` 字段构建结构化新数组,同时处理缺失键(如 `note` 不存在时默认为空字符串)。
在 PHP 开发中,常需对 JSON 数据解析后的多维关联数组进行条件过滤与字段重组。原始数据以 Swift 代码为键(如 "40E"、"43P"),每个键对应一个包含 id、swift_code、status 和可选 note 的子数组。目标是:仅当 status == 2 时,提取该条目的 swift_code 和 note(若不存在则设为空字符串),最终生成一个索引数字键的新数组。
首先,必须将原始 JSON 字符串正确解析为 PHP 关联数组(使用 json_decode($json, true))。注意:问题中给出的“数组”实际是 JavaScript 对象字面量语法,PHP 无法直接执行,必须通过 json_decode() 转换:
<?php $json = '{
"40E": {
"id": 94,
"swift_code": "40E",
"status": 1
},
"43P": {
"id": 106,
"swift_code": "43P",
"status": 2,
"note": "Allowed (INSTEAD OF EXISTING)"
},
"27": {
"id": 106,
"swift_code": "27",
"status": 2,
"note": "Allowed"
}
}';
$businesscommercialArray = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Invalid JSON input');
}接着,使用 foreach 遍历顶层键值对。关键点在于:外层循环的 $value 即为每个 Swift 条目(如 ["id"=>106, "swift_code"=>"43P", ...]),无需嵌套循环——原问题中错误地对 $values 再次 foreach,导致取到的是单个字段值(如 94 或 "40E"),而非完整条目。
正确做法是逐项检查 status,并利用空合并运算符 ?? 安全访问可能缺失的 note:
$finalArray = [];
foreach ($businesscommercialArray as $entry) {
if (isset($entry['status']) && $entry['status'] == 2) {
$finalArray[] = [
'swift_code' => $entry['swift_code'] ?? '',
'note' => $entry['note'] ?? ''
];
}
}
print_r($finalArray);
// 输出:
// Array
// (
// [0] => Array
// (
// [swift_code] => 43P
// [note] => Allowed (INSTEAD OF EXISTING)
// )
// [1] => Array
// (
// [swift_code] => 27
// [note] => Allowed
// )
// )⚠️ 注意事项:
- 始终校验
json_decode()结果,避免因 JSON 格式错误导致$businesscommercialArray为null; - 使用
isset($entry['status'])防止未定义索引警告; -
??运算符比三元isset() ? :更简洁,但要求 PHP ≥ 7.0; - 若需保留原始键(如
"43P")作为新数组键,可改为$finalArray[$entry['swift_code']] = [...]; - 如需严格区分
status === 2(整型),建议用全等比较,避免类型隐式转换风险。
此方案结构清晰、健壮性强,适用于各类基于状态筛选并投影字段的数组处理场景。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











