首页 > 解决方案 > 如何使用 PHP 从 JSON 响应中的列表中提取特定值?

问题描述

我正在执行一个 API 请求,它会给出这样的 JSON 响应 -

在此处输入图像描述

这个 JSON 对我来说太复杂了,所以我一直在寻找一种方法来消除无用的东西。我想要的最终 JSON 应该看起来像这样 -

在此处输入图像描述


这意味着,我将删除列表中以外Display的所有项目records,并将它们全部添加到一个单独的列表中,该列表仅包含显示值。是否可以使用 PHP 修改 JSON?

您的帮助/建议将不胜感激!

标签: phpjsonparsing

解决方案


这就是您需要做的 - 将您的 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"}

推荐阅读