0

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: [
        "[email protected]"
        ]
    },
    {
        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 Answer 1

3

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];
// [email protected]

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)

Sign up to request clarification or add additional context in comments.

2 Comments

@Omar Not directly, but there is an array_column polyfill for versions earlier than 5.5 here: github.com/ramsey/array_column
Yes!! I wasnt able to test without this include because I have 5.4. Thank you so much! This did it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.