Reputation: 470
I want to get the last element in the JSON decoded array, Error I am getting
Warning: end() expects parameter 1 to be array
$data
output
stdClass Object (
[contact001] => stdClass Object ( [age] => 33 [name] => Robert [tel] => 87778787878787878 )
[contact002] => stdClass Object ( [age] => 33 [name] => Calvin [tel] => 87778787878787878 )
)
PHP code:
$namejson = $firebase->get(DEFAULT_PATH . '/name/');
$data=json_decode($namejson);
foreach ($data as $key => $value) {
echo end($key);
}
Warning: end() expects parameter 1 to be array
Upvotes: 0
Views: 2910
Reputation: 511
$namejson = $firebase->get(DEFAULT_PATH . '/name/');
$data=json_decode($namejson,true);
foreach ($data as $key => $value) {
echo end($value);
}
Upvotes: 0
Reputation: 54841
When you decode your $namejson
json string to array, you can use array_keys
to get array of keys, that are present in your array. Next, you need the last key from this array, use array_pop
for this. And because the last key is a string, you can use simple ++
operator to increment the value:
$data = json_decode($namejson, true);
$keys = array_keys($data);
$last_key = array_pop($keys);
echo 'Last key: ' . $last_key;
$last_key++;
$next_key = $last_key;
echo 'Next key: ' . $next_key;
Upvotes: 5