Search code examples
phpmysqlarraysopenidvar-dump

Search through JSON to build MySQL Insert?


I am attempting to integrate an OpenID login system on my website. I've used the provided code and the login system does properly return my data and it is being stored successfully in PHP.

Data returned from OpenID:

Array
(
    [family_name] => Doe
    [name] => John Doe
    [account_type] => BUSINESS
    [given_name] => John
    [address] => Array
        (
            [postal_code] => 12345
            [locality] => Test
            [region] => NE
            [country] => US
            [street_address] => 123 Main Street
        )

    [verified_account] => true
    [language] => en_US
    [zoneinfo] => America/Chicago
    [locale] => en_US
    [phone_number] => 5553891234
    [email] => johndoe@test.com
    [account_creation_date] => 2008-03-06
    [birthday] => 2000-01-01
    [age_range] => 18-25
) 

I am then converting the JSON to an array with var_dump.

When printing the data after the var_dump, my data is as follows:

array(14) { ["family_name"]=> string(9) "Doe" ["name"]=> string(13) "John Doe" ["account_type"]=> string(8) "BUSINESS" ["given_name"]=> string(3) "John" ["address"]=> array(5) { ["postal_code"]=> string(5) "12345" ["locality"]=> string(5) "Test" ["region"]=> string(2) "NE" ["country"]=> string(2) "US" ["street_address"]=> string(32) "123 Main Street" } ["verified_account"]=> string(4) "true" ["language"]=> string(5) "en_US" ["zoneinfo"]=> string(15) "America/Chicago" ["locale"]=> string(5) "en_US" ["phone_number"]=> string(10) "5553891234" ["email"]=> string(20) "johndoe@test.com" ["account_creation_date"]=> string(10) "2008-03-06" ["birthday"]=> string(10) "2000-01-01" ["age_range"]=> string(5) "18-25" }

Now my question becomes (and this is where I am stuck) how do I loop through the array and pull out just the data? I am attempting to build a MySQL insert off of the data for creating user accounts.

I'd rather not just assume that the user's last name will be the first thing stored in the array. Is there a way to easily search the array and return only the data?

I've taken a look at print_r and a few other methods but everything seems to return ["family_name"]=> string(9) "Doe" instead of just Doe.


Solution

  • if you have the JSON string you can use json_decode() which will turn it into an array. You can then get the value of any of the properties by using regular array syntax..

    eg.

    $user_info = json_decode($json_string, true);
    $family_name = $user_info["family_name"]