Skip to content
Advertisement

Access JSON Array Data Within Object With PHP

stdClass Object ( 
[id] => 8586332 
[email] => hello@myemail.com 
[optInType] => Unknown 
[emailType] => Html 
[dataFields] => Array 
( 
[0] => stdClass Object ( [key] => FIRSTNAME [value] => Bill ) 
[1] => stdClass Object ( [key] => FULLNAME [value] => Bill Jones ) 
[2] => stdClass Object ( [key] => GENDER [value] => ) 
[3] => stdClass Object ( [key] => LASTNAME [value] => Jones ) 
[4] => stdClass Object ( [key] => LASTSUBSCRIBED [value] => 2019-12-20T21:13:20.359947Z ) 
[5] => stdClass Object ( [key] => POSTCODE [value] => ) 
[6] => stdClass Object ( [key] => THIS_KEY [value] => This Value ) 
) 
[status] => Subscribed )

I have this JSON object and array in PHP that I have decoded.

I am trying to access ‘This Value’ but I am stuck.

I also need to find a way to do it where I don’t know if it will always be number 6.

I have made these attempts:

$object->{"dataFields[1]"};

and

$object['dataFields'][6]['THIS_KEY'];

I can access the email like this:

echo $objec[1]->email;

Advertisement

Answer

You will need to search through the subarray for the qualifying object using the key property’s value.

There will be functional techniques to do this, but I’ll show a simple loop and break technique.

Code: (Demo)

$object = (object) [
    'id'=> 8586332,
    'email' => 'hello@myemail.com',
    'optInType' => 'Unknown',
    'emailType' => 'Html',
    'dataFields' => [
        (object)['key' => 'FIRSTNAME', 'value' => 'Bill'],
        (object)['key' => 'FULLNAME', 'value' => 'Tom Jones'],
        (object)['key' => 'GENDER', 'value' => ''],
        (object)['key' => 'LASTNAME', 'value' => 'Jones'],
        (object)['key' => 'LASTSUBSCRIBED', 'value' => '2019-12-20T21:13:20.359947Z'],
        (object)['key' => 'POSTCODE', 'value' => ''],
        (object)['key' => 'THIS_KEY', 'value' => 'This Value'],
    ],
    'status' => 'Subscribed'
];

foreach ($object->dataFields as $dataRow) {
    if ($dataRow->key === 'THIS_KEY') {
        echo $dataRow->value;
        break;
    }
}

Output:

This Value

A functional search can look like this: (Demo)

$index = array_search('THIS_KEY', array_column($object->dataFields, 'key'));
if ($index !== false) {
    echo $object->dataFields[$index]->value; // same output as above
}

If you want simpler access to multiple values in the subarray, then assign temporary keys: (Demo)

$assocDataFields = array_column($object->dataFields, null, 'key');

echo $assocDataFields['THIS_KEY']->value;
echo "n";
echo $assocDataFields['FULLNAME']->value;

Output:

This Value
Tom Jones
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement