【问题标题】:How to extract specific values from a list in JSON response with PHP?如何使用 PHP 从 JSON 响应中的列表中提取特定值?
【发布时间】:2021-11-22 22:56:49
【问题描述】:

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

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


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

我们将非常感谢您的帮助/建议!

【问题讨论】:

标签: php json parsing


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多