>  기사  >  백엔드 개발  >  关于获取api返回json的处理

关于获取api返回json的处理

WBOY
WBOY원래의
2016-06-06 20:21:381712검색

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

<code>{"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"}}</code>

回复内容:

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

<code>{"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"}}</code>

array_shift();

<code>$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;
}</code>

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

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.