Tonzkie
Tonzkie

Reputation: 549

Parse json value

Hi I'm trying to parse this value from zoo component Joomla database.

{ 
    "1f1292f5-0d8f-4c53-9260-07b074aa5bf1": { "0": { "value": "lit_ZetaPlus_zeta_potential_analyzer.html" } },
    "26a0f41d-5514-4855-9cb2-175b662fe350": { "0": { "value": "ZetaPlus" } }, 
    "9ab61998-c48e-45d7-8160-e563ba81b851": { "0": { "value": "Zeta Potential Analyzers" } }, 
    "2616ded9-e88b-4b77-a92c-2c4c18bb995f": { "0": { } }, 
    "08795744-c2dc-4a68-8252-4e21c4c4c774": { "0": { } }, 
    "2e3c9e69-1f9e-4647-8d13-4e88094d2790": { "0": { } }, 
    "fdcbebaa-e61a-462d-963e-aff74ff95499": { "0": { } } 
}

After 4 hours of turning it to an array then to an object I failed so far. Would appreciate help on what I'm doing wrong. This is what I got so far.

$decode = (array) json_decode($row['elements']);

foreach ($decode as $values) {
    echo $values[0];
}

Upvotes: 1

Views: 98

Answers (1)

cmbuckley
cmbuckley

Reputation: 42458

Use the second parameter of json_decode (documentation):

$decoded = json_decode($row['elements'], true);

This gives you the decoded JSON as an associative array rather than an object.

Your cast to an array is not recursive, so it will only change the top-level object to an array. All objects within the collection will remain as objects.

If you leave your JSON as objects, you may struggle to access numeric keys, as $value->0 won't work. You'd need to do $value->{'0'} instead. So the associative array may be the easier option :-)

Upvotes: 3

Related Questions