欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

关于获取api返回json的处理

程序员文章站 2024-01-08 12:14:16
...
以下是api获取的数据,怎么获取到第一组数据呢?只要一组
也就是"20151224084":{"number":"9,7,6,8,0","dateline":"2015-12-24 20:02:55"}这个。
{"20151224084":{"number":"9,7,6,8,0","dateline":"2015-12-24 20:02:55"},"20151224083":{"number":"4,2,7,5,1","dateline":"2015-12-24 19:52:55"},"20151224082":{"number":"6,5,5,5,7","dateline":"2015-12-24 19:43:36"},"20151224081":{"number":"3,8,6,0,8","dateline":"2015-12-24 19:33:01"},"20151224080":{"number":"5,1,6,7,9","dateline":"2015-12-24 19:23:01"},"20151224079":{"number":"3,8,0,3,5","dateline":"2015-12-24 19:13:05"},"20151224078":{"number":"1,2,2,8,4","dateline":"2015-12-24 19:02:57"},"20151224077":{"number":"1,4,9,1,1","dateline":"2015-12-24 18:52:58"},"20151224076":{"number":"3,2,4,0,3","dateline":"2015-12-24 18:43:25"},"20151224075":{"number":"0,3,2,9,7","dateline":"2015-12-24 18:32:59"}}

回复内容:

以下是api获取的数据,怎么获取到第一组数据呢?只要一组
也就是"20151224084":{"number":"9,7,6,8,0","dateline":"2015-12-24 20:02:55"}这个。

{"20151224084":{"number":"9,7,6,8,0","dateline":"2015-12-24 20:02:55"},"20151224083":{"number":"4,2,7,5,1","dateline":"2015-12-24 19:52:55"},"20151224082":{"number":"6,5,5,5,7","dateline":"2015-12-24 19:43:36"},"20151224081":{"number":"3,8,6,0,8","dateline":"2015-12-24 19:33:01"},"20151224080":{"number":"5,1,6,7,9","dateline":"2015-12-24 19:23:01"},"20151224079":{"number":"3,8,0,3,5","dateline":"2015-12-24 19:13:05"},"20151224078":{"number":"1,2,2,8,4","dateline":"2015-12-24 19:02:57"},"20151224077":{"number":"1,4,9,1,1","dateline":"2015-12-24 18:52:58"},"20151224076":{"number":"3,2,4,0,3","dateline":"2015-12-24 18:43:25"},"20151224075":{"number":"0,3,2,9,7","dateline":"2015-12-24 18:32:59"}}

array_shift();

$json = '{"20151224084":{"number":"9,7,6,8,0","dateline":"2015-12-24 20:02:55"},"20151224083":{"number":"4,2,7,5,1","dateline":"2015-12-24 19:52:55"},"20151224082":{"number":"6,5,5,5,7","dateline":"2015-12-24 19:43:36"},"20151224081":{"number":"3,8,6,0,8","dateline":"2015-12-24 19:33:01"},"20151224080":{"number":"5,1,6,7,9","dateline":"2015-12-24 19:23:01"},"20151224079":{"number":"3,8,0,3,5","dateline":"2015-12-24 19:13:05"},"20151224078":{"number":"1,2,2,8,4","dateline":"2015-12-24 19:02:57"},"20151224077":{"number":"1,4,9,1,1","dateline":"2015-12-24 18:52:58"},"20151224076":{"number":"3,2,4,0,3","dateline":"2015-12-24 18:43:25"},"20151224075":{"number":"0,3,2,9,7","dateline":"2015-12-24 18:32:59"}}';
$data = json_decode($json,true);
// 方法1
$want = $data['20151224084']; 
// 方法2
$want = array_pop(array_reverse($data,true));
// 最笨的办法
$want = [];
foreach($data as $key=>$value){
  $want = [$key=>$value];
  break;
}

说明一下:第二种方式有个坑,就是当数组的长度特别长时,比如1000、10000,数组的翻转是一件很消耗性能的操作,所以,根据你的实际情况借鉴性的使用,第三种方式虽然笨,但是性能不错。
经友情提醒,刚才忘记了array_shift

json_decode($string, true)
转为数组后你肯定会了。

相关标签: php