Jump to content

Recommended Posts

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

1 hour ago, Rascalsailor said:

(can I not point to a specific element?)

Of course you can.

foreach() is for iterating through all elements in an array. In this case you don't want to do that.

$arr = json_decode($jsn, 1);
$elem = $arr['identifiers'][0]['device_ids'];

echo $elem['application_ids']['application_id'] . '<br>';
echo $elem['dev_eui'] . '<br>';
echo $elem['device_id'] . '<br>';

However, are you certain that the "identifiers" array will only have a single element? If the number is unknown, use foreach()...

$arr = json_decode($jsn, 1);
foreach ( $arr['identifiers'] as $ids ) {
    $elem = $ids['device_ids'];
    echo $elem['application_ids']['application_id'] . '<br>';
    echo $elem['dev_eui'] . '<br>';
    echo $elem['device_id'] . '<br>';
}

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.