Accessing JSON object elements in PHP

32,237

If you are using json_decode($json,true); - true means returning the js objects results as associative arrays - then all you have to do is $user_info = $jsonDecoded['USER']; without the array() cast cause that is what json_decode do for you.

If you would choose to omit the second boolean parameter then you will get an stdClass which $jsonDecoded->USER; would work for you

Share:
32,237
Admin
Author by

Admin

Updated on April 30, 2020

Comments

  • Admin
    Admin about 4 years

    I have a JSON object that I'm POST'ING to PHP from ExtJS interface. I get the object from

    $json = $_POST["newUserInfo"];
    

    The object will contain 3 arrays, which I can see if I do

    var_dump(json_decode($json));
    

    I need to take each array and build SQL queries from them. My first obstacle is getting the arrays out of the object, though this may be unnecessary. Here is the code block I'm working from:

    /*Variable passed in from the ExtJS interface as JSON object*/
    $json = $_POST["newUserInfo"];
    //$json = '{"USER":{"ID":"","FULL_USER_NAME":"Some Guy","ENTERPRISE_USER_NAME":"guyso01","USER_EMAIL":"[email protected]","USER_PHONE":"123-456-7890"},"PERMISSIONS":{"ID":"","USER_ID":"","IS_ADMIN":"true"},"SETTINGS":{"ID":"","USERS_ID":"","BACKGROUND":"default"}}';
    
    //Test to view the decoded output
    //var_dump(json_decode($json));
    
    //Decode the $json variable
    $jsonDecoded = json_decode($json,true);
    
    //Create arrays for each table from the $jsonDecoded object
    $user_info = array($jsonDecoded['USER']);
    $permissions_info = array($jsonDecoded['PERMISSIONS']);
    $settings_info = array($jsonDecoded['SETTINGS']);  
    

    I'm not creating the arrays correctly. I've also tried

    $user_info = $jsonDecoded->USER;
    

    and that doesn't work either. I'm sure I'm missing something easy here. Again, this may be unnecessary as I can probably access them directly. I need to build the query by looping through the array and appending each key to a string and each value to a string. So I'd end up with something like

    $query = "INSERT INTO USERS ($keyString) VALUES ($valueString);
    

    Then I'd repeat the same process for PERMISSIONS and SETTINGS arrays. This is probably simple but I'm stuck here.

  • Admin
    Admin about 11 years
    Thanks @Adidi. I knew it was something simple that I was missing. Now I can just loop each array and call array_keys and array_values to get the key->value pairs for the query string.