ben ben - 3 years ago 211
PHP Question

JSON decode get the last element, PHP end

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

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download