I’ve got a set of "objects", each of which has an ID, and couple or properties. I want to store this in JSON format in a file. In the application, I first need to show a list of all "objects" with its properties. Secondly, I need to access one entry by its ID and only work with those properties.
The JSON file looks like this:
{
"ID-001": {
"Tag1": "value1a",
"Tag2": "value1b"
},
"ID-002": {
"Tag1": "value2a",
"Tag2": "value2b"
},
"ID-003": {
"Tag1": "value3a",
"Tag2": "value3b"
}
}
In this sample PHP code, I know how to work with properties, given I already have the onject’s ID, and I can list a specific property for all objects.
<?php
$objects = json_decode(file_get_contents("sample.json", TRUE), FALSE);
var_dump($objects) ."n";
print "-----------------------------------------n";
$ix = "ID-001";
if (!isset($objects->$ix)) {
print "Key {$ix} does not exist." . "n";
} else {
print "Tag1 has value: {$objects->$ix->Tag1}n";
}
$ix = "ID-004";
if (!isset($objects->$ix)) {
print "Key {$ix} does not exist." . "n";
} else {
print "Tag1 has value: {$objects->$ix->Tag1}n";
}
print "-----------------------------------------n";
foreach ($objects as $object) {
print "Tag1 has value: {$object->Tag1}n";
}
?>
What I can’t seem to find out, is how I can access the ID of the objects in a loop, so get a list of IDs. Can I?
2
Answers
Olá, tente isso:
}
You are almost there
Here’s how you can modify your foreach loop to access the IDs: