Rascalsailor
-
Posts
2 -
Joined
-
Last visited
Posts posted by Rascalsailor
-
-
Hi all
I have the following file of json data (json_file.json):
{ "name": "as.up.data.forward", "time": "2022-07-27T09:46:50.565402155Z", "identifiers": [{ "device_ids": { "device_id": "my_arduino-device", "application_ids": { "application_id": "mydevicename" }, "dev_eui": "012345678910", "join_eui": "109876543210", "dev_addr": "123456" } }] }
I am using the following code to extract and display some of the data:
<?php $json = file_get_contents('json_file.json'); // Decode the JSON file $json_data = json_decode($json,true); $identifiers_array = ($json_data['identifiers']); foreach($identifiers_array as $elem) { print_r($elem['device_ids']['application_ids']['application_id']); echo("<br/>"); print_r($elem['device_ids']['dev_eui']); echo("<br/>"); print_r($elem['device_ids']['device_id']); } ?>
The output as expected, shows:
mydevicename 012345678910 my_arduino-device
My Question is:
Can I not avoid the use of the foreach by doing something along the lines of:
print_r($identifiers_array['device_ids']['application_ids']['application_id']);
(can I not point to a specific element?)
I'm really just wondering if I am following a 'best practice' method here.
Thanks
Russell
DO I need foreach for accessing specific array data here?
in PHP Coding Help
Posted · Edited by Rascalsailor
Great, thanks for the reply. The trick was to use: $elem = $arr['identifiers'][0]['device_ids'];
That indexing : [0] was confusing me.
regards
Russell