PHP中json_decode后如何访问多维数组内的tokenName字段
PHP访问嵌套数组tokenName字段失败修复方案
问题根因
调用json_decode($data, true)时,第二个参数传true会将JSON内容解析为纯关联数组,而非对象,所有层级的元素都需要用数组下标方式访问。原有写法混合了对象操作符、下标序号错误、键名未加引号、遍历层级错误,导致无法读取result数组内的字段。
涉及的目标数组结构如下:
Array ( [status] => 1 [message] => OK [result] => Array ( [0] => Array ( [contractAddress] => 0x3845badAde8e6dFF049820680d1F14bD3903a5d0 [tokenName] => SAND [symbol] => SAND [divisor] => 18 [tokenType] => ERC20 [totalSupply] => 3000000000 [blueCheckmark] => true [description] => The Sandbox is a virtual world where players can build, own, and monetize their gaming experiences in the Ethereum blockchain using SAND, the platform’s utility token. [website] => http://www.sandbox.game/ [email] => contact@sandbox.game [blog] => XX [reddit] => [slack] => [facebook] => XX [twitter] => XX [bitcointalk] => [github] => XX [telegram] => https://t.me/sandboxgame [wechat] => [linkedin] => XX [discord] => XX [whitepaper] => https://installers.sandbox.game/The_Sandbox_Whitepaper_2020.pdf [tokenPriceUSD] => 1.290000000000000000 ) ) )
原有写法的错误点
- 对纯数组使用
->对象操作符访问:$curl_jason->message、$curl_jason->result[telegram]、$curl_jason[result][1]->tokenName均属于语法错误 - 对字符串键的关联数组使用数字顺序下标:
$curl_jason[3][0]写法错误,顶层数组的键为status/message/result,不存在数字下标3 - 数组字符串键未加引号:裸写的
result、telegram会被PHP识别为未定义常量,触发警告并返回错误结果 - 子数组下标错误:
result下的索引数组从0开始计数,写[1]访问的是第二个元素,当前结构中该下标不存在 array_column调用层级错误:直接传入顶层数组只会遍历顶层键,顶层不存在tokenName字段,无法拿到结果
正确访问代码
直接读取单个tokenName值
$curl_json = json_decode($curl_response, true); // 按层级访问:顶层result键 → 索引0的子项 → tokenName键 echo $curl_json['result'][0]['tokenName']; // 输出结果:SAND
批量读取result下所有tokenName
如果result下存在多个代币条目,用array_column提取的正确写法:
$tokenNameList = array_column($curl_json['result'], 'tokenName'); print_r($tokenNameList);
同层级其他字段访问示例
比如读取telegram字段:
echo $curl_json['result'][0]['telegram'];
内容的提问来源于stack exchange,提问作者Adam Page
相关产品推荐
相关产品推荐

