
本文详细讲解如何使用 json_decode() 将深层嵌套的 JSON 字符串转换为 PHP 对象(或数组),并安全、准确地访问如 transaction_reference 和 status 等多层嵌套字段,避免因路径错误或类型误判导致的空值或报错。
本文详细讲解如何使用 `json_decode()` 将深层嵌套的 json 字符串转换为 php 对象(或数组),并安全、准确地访问如 `transaction_reference` 和 `status` 等多层嵌套字段,避免因路径错误或类型误判导致的空值或报错。
在 PHP 中处理嵌套 JSON 时,关键在于理解其结构层级,并严格遵循对象属性访问语法(当使用默认的 json_decode($json) 即 assoc = false 时)。原始 JSON 包含多层嵌套:外层 data → attributes → transfer_batches(数组)→ disbursements(数组)→ 最终目标字段。直接写 $jsonData->status 会失败,因为 status 并非根对象的直系属性,而是位于 data->attributes->status 路径下。
以下是一个完整、健壮的解析示例:
<?php
// 假设 $response 是接收到的原始 JSON 字符串
$response = '{
"data": {
"id": "1cc58ad2-ccfd-4ede-a6a6-35809c81cb8a",
"type": "payment",
"attributes": {
"status": "Sent",
"created_at": "2022-05-02T08:57:50.171+03:00",
"amount": { "currency": "KES", "value": "500.0" },
"transfer_batches": [{
"status": "Sent",
"amount": "500.0",
"disbursements": [{
"amount": "500.0",
"status": "Transferred",
"origination_time": "2022-05-02T08:57:50.171+03:00",
"transaction_reference": "1651471070",
"destination_type": "till",
"destination_reference": "3eccf0c1-ab6b-41a4-b51a-4e8f588105f1"
}]
}],
"metadata": { "something": "TST-01" },
"_links": { "callback_url": "http://portal.zarafu.com/payments" }
}
}
}';
// 第一步:解码为 stdClass 对象(默认行为)
$jsonData = json_decode($response);
// 第二步:逐层访问嵌套属性(注意:数组索引需用 ->0, ->1 等,不可用 ["0"])
if ($jsonData && isset($jsonData->data->attributes)) {
// ✅ 正确获取顶层 status
$paymentStatus = $jsonData->data->attributes->status ?? 'unknown';
// ✅ 正确获取 transaction_reference(需确保数组存在且非空)
$disbursement = $jsonData->data->attributes->transfer_batches[0]->disbursements[0] ?? null;
$transactionRef = $disbursement ? ($disbursement->transaction_reference ?? 'N/A') : 'N/A';
echo "Payment Status: {$paymentStatus}\n";
echo "Transaction Reference: {$transactionRef}\n";
} else {
error_log('Invalid or malformed JSON response');
}⚠️ 重要注意事项:
- json_decode() 默认返回 stdClass 对象,不能用数组语法(如 $jsonData['data'])访问;若需数组形式,应显式传入 true:json_decode($response, true),此时路径变为 $data['data']['attributes']['status']。
- transfer_batches 和 disbursements 是数组,必须用 [0](而非 ->0)访问——上文答案中 ->0 的写法仅在极旧版本 PHP 或特定配置下偶然生效,实际为错误示范。正确写法始终是方括号索引:$jsonData->data->attributes->transfer_batches[0]->disbursements[0]->transaction_reference。
- 务必添加 isset() 或空合并操作符(??)进行防御性编程,防止因某一层缺失导致 Notice: Trying to get property of non-object 错误。
- 生产环境中建议配合 json_last_error() 检查解码是否成功,并对非法 JSON 提供清晰错误反馈。
总结:解析嵌套 JSON 的核心是「结构即路径」——先画出 JSON 树状图,再严格按层级+类型(对象用 ->,数组用 [i])拼接访问链,并始终做存在性校验。掌握这一模式,即可高效、可靠地提取任意深度的字段。
立即学习“PHP免费学习笔记(深入)”;



















