我正在尝试弄清楚如何使用PHP从最后一个JSON对象获取数据。
以下是包含3个对象的JSON的副本:
[
{
"url":"http://example1.com",
"identifier":495755330,
"current_date":"2015-12-30 17:05:45",
"results":3,
"networks":{
"FaceBook":{"detected":true,"result":"no-result"},
"Twitter Inc":{"detected":false,"result":"no-result"},
"Pinterest.com":{"detected":true,"result":"no-result"},
"Other Sites":{"detected":true,"result":"some-result"}
}
},
{
"url":"http://example2.com",
"identifier":495755331,
"current_date":"2015-12-30 17:05:46",
"results":0,
"networks":{
"FaceBook":{"detected":false,"result":"what-result"},
"Twitter Inc":{"detected":false,"result":"some-result"},
"Pinterest.com":{"detected":false,"result":"some-result"},
"Other Sites":{"detected":false,"result":"what-result"}
}
},
{
"url":"http://example3.com",
"identifier":495755332,
"current_date":"2015-12-30 17:05:47",
"results":1,
"networks":{
"FaceBook":{"detected":false,"result":"some-result"},
"Twitter Inc":{"detected":true,"result":"some-result"},
"Pinterest.com":{"detected":false,"result":"some-result"},
"Other Sites":{"detected":false,"result":"some-result"}
}
}
]
我希望获得每个数组中最后一个对象的identifier
。在上面的示例中,这将是495755332
。
以下是我获取JSON数据的方法:
$filename = 'https://www.example.com';
$json = file_get_contents($filename);
$data = json_decode($json, true);
我无法弄清楚如何从最后一个对象获取identifier
并将其输出到文本文件。
答案 0 :(得分:3)
很简单,如果它总是成为数组中的最后一个元素,请使用end()
:
$filename = 'https://www.example.com';
$json = file_get_contents($filename);
$data = json_decode($json, true);
$last = end($data);
// now echo
echo $last['identifier'];
如果失败,只需使用数组中的最后一个元素:
echo $data[count($data) - 1]['identifier'];
答案 1 :(得分:0)
第一种情况是使用end
函数:
$filename = 'https://www.example.com';
$json = file_get_contents($filename);
$data = json_decode($json, true);
$last_identifier = end($data)['identifier'];
第二种情况是使用array_pop
提取最后一个数组元素:
...
$data = json_decode($json, true);
$last_identifier = array_pop($data)['identifier'];