dongzi1209 2018-02-17 21:53
浏览 1084
已采纳

如何在php中读取多级json的值?

I have the following code to read a Json and store some values into an array:

<?php
$json = '[{
        "provider_id":1,
        "nro_chart":1,
        "control": {
            "color": "blue",
            "total_value": 21.5,
            "car_id": 421118
        }
    },
    {
        "control": {
            "color": "green",
            "total_value": 25,
            "car_id": 421119
        }
    },
    {
        "control": {
            "color": "red",
            "total_value": 18,
            "car_id": 421519
        }
    }
]';

$j = json_decode($data);
$result = [];
foreach ($j as $item) {
    array_push($result,[
        'total_value' => $item->control->total_value,
        'car_id' => $item->control->car_id
    ]);
}

Now I need to get the two values that are outside of "control" like "provider_id" and "nro_chart" inside a variable.

  • 写回答

3条回答 默认 最新

  • duanjiuhong5843 2018-02-17 21:58
    关注

    The JSON contains an array of one element, so to access provider_id and nro_chart, get the first element and directly access the properties:

    $j = json_decode($json);
    var_dump($j[0]->provider_id); // /Applications/MAMP/htdocs/trello/up.php:28:int 1
    var_dump($j[0]->nro_chart); // /Applications/MAMP/htdocs/trello/up.php:28:int 1
    

    Demo

    Or, within that same foreach loop:

    foreach ($j as $item) {
        array_push($result,[
            'total_value' => $item->control->total_value,
            'car_id' => $item->control->car_id
        ]);
        if (isset($item->provider_id)) {
            var_dump($item->provider_id);
        }
        if (isset($item->nro_chart)) {
            var_dump($item->nro_chart);
        }
    }
    

    Be sure to check if the property is set for that element with isset() first.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 Spring MVC项目,访问不到相应的控制器方法
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on 192.168.154.223发生意外错误: 5无法连接到 MQTT 代理,如何解决?
  • ¥15 关于#genesiscsheel#的问题,如何解决?
  • ¥15 Android aidl for hal
  • ¥15 STM32CubeIDE下载程序报错
  • ¥15 微信好友如何转变为会员系统?(相关搜索:小程序)
  • ¥15 c# 直接使用c++ 类库文件
  • ¥15 一个主机电脑有两个显示器,当前有两个软件主体是网页html打包的exe程序,如何通过cmd命令bat同时打开软件一个在主屏幕显示,另外一个软件在2副屏幕上显示