douhan4243 2018-05-14 16:24
浏览 35
已采纳

解析JSON而不依赖于订单

I have this JSON, I'm parsing. I can retrieve all the values of field_data in order in PHP, but I need to traverse and get the values I wan't by specifying the field name, without concern for order:

JSON

{
   created_time: "2018-05-14T16:11:02+0000",
   id: "555555555555",
   field_data: [
   {
        name: "bedrooms_interested_in?",
        values: [
        "2"
        ]
    },
    {
        name: "When_are_you_looking?",
        values: [
        "January 1s 2019"
        ]
    },
    {
        name: "email",
        values: [
        "xxxx@domain.com"
        ]
    },
    {
        name: "full_name",
        values: [
        "John Michael"
        ]
    },
    {
        name: "phone_number",
        values: [
        "+15555555555"
        ]
    }
    ]
}

PHP

This is grabbing the last 3 fields. I'm currently able to pull the fields_data in order like this, but how could I grab the value fields I want by specifying the name field I'm looking for?

   $data = json_decode($response, true);
    // var_dump($data);
        file_put_contents('dump.txt', $response);
    $lead_email = $data['field_data'][2]['values'][0];
    $lead_fullname = $data['field_data'][3]['values'][0];
    $lead_phone = $data['field_data'][4]['values'][0];
  • 写回答

1条回答 默认 最新

  • duanmanmian7589 2018-05-14 16:31
    关注

    You can use array_column to re-index an array by a given column, which will give you easier and more reliable access to the data:

    $data['field_data'] = array_column($data['field_data'], null, 'name');
    

    This allows you to access fields by name instead of their numeric index, e.g.

    echo $data['field_data']['email']['values'][0];
    // xxxx@domain.com
    

    See https://eval.in/1003874 for a full example

    (Note, I added some quotes to your JSON property names, since they were missing in the question. I assume that's a formatting issue, since this wouldn't work at all otherwise)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值