有很多像这样的类似问题 - 我几乎在Stack上阅读了所有这些问题,并且无法绕过它。
我正在使用CURL解码json文件。我正在检索内容的网址是https://api.mojang.com/user/profiles/e6e37a93864f496383ba362df30f4792/names。
在我正确地将数组转换为PHP数组后,我试图返回PHP数组中的最后一项。
我试图使用array_pop,但我无法使用它。我使用计数来计算数组中的总行数,并引用最后一行。
$data = json_decode($output);
$count = count($data);
return $data[$count]['name'];`
我甚至试图做
return $data[$count]['name']->name; // OR...
return $data[$count]->name;
这是因为
return $data[0]->name;
返回“Eli_Silveraxe”,这是数组中的值,但不是最后一个值。这些选项都没有对我有用,而且只会变得更加令人沮丧,因为我可以返回Eli_Silveraxe,而不是“Malfunction”,这应该是返回的。
你能帮忙吗?
答案 0 :(得分:0)
请试试这个
$data = json_decode($output, true);
$count = count($data) - 1;
return $data[$count]['name'];
答案 1 :(得分:0)
数组中的最后一项的索引为count - 1
,因此您需要:
$data = json_decode($output);
$count = count($data);
return $data[$count - 1]->name;
请注意,您无需将第二个参数传递给json_decode
(或传递false
)以获取$data
中的对象。或者,传递true
并使用关联数组语法:
$data = json_decode($output, true);
$count = count($data);
return $data[$count - 1]['name'];