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)

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

报告相同问题?