Reputation: 2246
Ok, so I have this in a JSON array (the output of retrievedData())
{
"device": {
"01AA02AB141208VV": {
"$version": -148598935,
"$timestamp": 1344382016000,
"serial_number": "01AA02AB141208VV"
}
}
}
However, I can't seem to select the serial number. I have tried what usually works, but I can't select it. This is assuming we don't already know the "01AA02AB141208VV".
$retrieved_data = retrieveData($array['userid'], $array['urls']['transport_url'], $array['access_token']);
$retrieved_data_array = json_decode($retrieved_data, true);
$serial_number = $retrieved_data_array['device'][0]['serial_number'];
Am I doing something wrong? I bet it's really simple, but I just cannot figure it out!
Thanks!
Upvotes: 1
Views: 97
Reputation: 8301
This will grab the serial numbers, assuming you have multiple items in the devices array:
$keys = array();
foreach( $retrieved_data_array['device'] as $key => $val ){
$keys[] = $key;
}
$serial = $keys[0];
This can be reduced if you know you only have one item in the array...
Upvotes: 1
Reputation: 3280
you can use key() function to access the keys of the associative array (in this case the '$retrieved_data_array['device']' array:
<?php
$data = '{"device": {"01AA02AB141208VV": {"$version": -148598935,"$timestamp": 1344382016000,"serial_number": "01AA02AB141208VV"}}}';
$retrieved_data_array = json_decode($data, true);
$serial_number = key($retrieved_data_array['device']);
reset($retrieved_data_array['device']);
print_r($serial_number);
print_r($retrieved_data_array['device'][$serial_number]);
?>
Upvotes: 3
Reputation: 39522
Unfortunately, it's not really simple. You're trying to find 42 Main St. when you don't know the city Main St. is located in. The only way to find the serial_number
would be to loop over $retrieved_data_array
with foreach
until you find the value you want.
Upvotes: 4