php - 如何使用 PHP 从 JSON 响应中的列表中提取特定值?
问题描述
我正在执行一个 API 请求,它会给出这样的 JSON 响应 -
这个 JSON 对我来说太复杂了,所以我一直在寻找一种方法来消除无用的东西。我想要的最终 JSON 应该看起来像这样 -
这意味着,我将删除列表中以外Display
的所有项目records
,并将它们全部添加到一个单独的列表中,该列表仅包含显示值。是否可以使用 PHP 修改 JSON?
您的帮助/建议将不胜感激!
解决方案
这就是您需要做的 - 将您的 json 解码为一个数组,遍历它并从中创建一个新数组,然后将新数组转换回 json!- 我为这个例子创建了一个接近你的模拟 json:
<?php
$json = '{"record":[
{
"id": "FirstId1",
"fields": {
"Display": "ADANI NAVINASH"
},
"created_time" : "20939290"
},
{
"id": "2ndId2",
"fields": {
"Display": "AGRWAL DDDDW"
},
"created_time" : "2343223455"
}
],
"offset": "dsfdgfdsg23432fd"
}';
$array = json_decode($json,true);
echo '<pre>';
print_r($array);
$newArray = []; //Set our new array;
foreach($array['record'] as $record){ //We loop to create our new array
$newArray['records'][] = $record['fields']['Display']; //add the Displays each to a different key
}
$newArray['offset'] = $array['offset']; // add the offset (only one and outside of record so out of the loop)
$newJson = json_encode($newArray); //At the end of it all we take our new array and turn it back to json!
print_r("The new Json: " . $newJson); // print our new json
这将返回:
Array
(
[record] => Array
(
[0] => Array
(
[id] => FirstId1
[fields] => Array
(
[Display] => ADANI NAVINASH
)
[created_time] => 20939290
)
[1] => Array
(
[id] => 2ndId2
[fields] => Array
(
[Display] => AGRWAL DDDDW
)
[created_time] => 2343223455
)
)
[offset] => dsfdgfdsg23432fd
)
The new Json: {"records":["ADANI NAVINASH","AGRWAL DDDDW"],"offset":"dsfdgfdsg23432fd"}
推荐阅读
- spring-mvc - 管理 URL,将路径附加到正确的所需位置
- php - MySQL - 从多个列中选择并忽略重复的结果
- python - Scipy不导入线性规划
- java - Oracle Java 教程 - 静态类 - 教程中可能出现的错误
- python - 如何以一种方式对python列表进行排序,如果1应该在之前,10和2在20之前
- python-2.7 - 如何使用随机密钥执行凯撒密码逻辑?
- java - 在 Android Studio 3.1.3 中构建 gradle 失败
- javascript - JS-Data addAction 方法抛出而不是拒绝带有错误消息的承诺
- react-native - 使用远程 MacBook 使用 XCode 构建 React Native 应用程序
- google-chrome-extension - 来自 chrome 扩展的调度事件清除事件数据传输