如何修改PHP JSON API,无需每次指定数组索引位置?
解决PHP JSON API需指定数组索引的问题
嘿,我来帮你搞定这个麻烦的索引问题!你现在的API返回结构里,store是一个由多个单元素数组组成的数组,每个字段(比如skuid、psplusprice)都单独占了一个数组位置,这就是为啥你必须用索引才能访问的原因。咱们只需要把这些零散的数组合并成一个单一的关联数组,就能实现你想要的直接用键名调用的效果。
修改后的API实现代码
// 先构建store的关联数组,直接把每个字段作为键值对放入 $storeData = [ 'name' => isset($store['included'][0]['attributes']['name']) ? $store['included'][0]['attributes']['name'] : '', 'skuid' => isset($store['included'][0]['attributes']['default-sku-id']) ? $store['included'][0]['attributes']['default-sku-id'] : '', 'releasedate' => isset($store['included'][0]['attributes']['release-date']) ? $store['included'][0]['attributes']['release-date'] : '', 'nonplusprice' => isset($store['included'][0]['attributes']['skus'][0]['prices']['non-plus-user']['actual-price']['display']) ? $store['included'][0]['attributes']['skus'][0]['prices']['non-plus-user']['actual-price']['display'] : '', 'psplusprice' => isset($store['included'][0]['attributes']['skus'][0]['prices']['plus-user']['actual-price']['display']) ? $store['included'][0]['attributes']['skus'][0]['prices']['plus-user']['actual-price']['display'] : '', 'filesize' => [ 'value' => isset($store['included'][0]['attributes']['file-size']['value']) ? $store['included'][0]['attributes']['file-size']['value'] : '', 'unit' => isset($store['included'][0]['attributes']['file-size']['unit']) ? $store['included'][0]['attributes']['file-size']['unit'] : '' ] // 后续新增字段直接按同样的键值对方式添加即可 ]; // 组装最终的API结构,把storeData直接作为store的值 $api = [ ['store' => $storeData] ]; return json_encode($api);
修改后的调用方式
现在你就可以直接通过键名访问想要的字段了,完全不用记那些容易搞混的索引:
$json = json_decode(你的API返回内容, true); // 注意第二个参数设为true,转为关联数组 echo $json[0]['store']['skuid']; // 直接获取sku id echo $json[0]['store']['psplusprice']; // 直接获取PS Plus价格 echo $json[0]['store']['filesize']['value']; // 获取文件大小数值 echo $json[0]['store']['filesize']['unit']; // 获取文件大小单位
关键修改点说明
- 原来的
store是array(array('name' => ...), array('skuid' => ...))这种数组套数组的结构,现在改成了array('name' => ..., 'skuid' => ...)的单一层关联数组,让每个字段直接对应一个键。 - 对于
filesize这种嵌套结构,直接把它作为store的一个键,值是包含value和unit的关联数组,既保持了结构清晰,又方便直接访问子字段。 - 这种修改不仅让API调用更直观,还能避免因为字段顺序变化导致的索引错误,后续维护和扩展也会轻松很多。
内容的提问来源于stack exchange,提问作者J. Doe
相关产品推荐
相关产品推荐

