Home >Backend Development >PHP Tutorial >主从结构的JSON要怎么分拆

主从结构的JSON要怎么分拆

WBOY
WBOYOriginal
2016-06-23 13:25:25909browse

$a='{"head":{"id":"4","userno":"12345","username":"CDZ1"},"body":[{"orderno":"1","price":"15.00","qty":"1"},{"orderno":"1","price":"9.00","qty":"1"}]}';

这样的一段jsoin,  我要单独取得head 部分的字段值及body 部份的字段值, 比如取 head 部份的 userno,及 body 部份的 price.


回复讨论(解决方案)

你 print_r(json_decode($a, 1)); 看一下,就知道该如何取得各分量了

你 print_r(json_decode($a, 1)); 看一下,就知道该如何取得各分量了




返回这个,
Array ( [head] => Array ( [id] => 4 [userno] => 13538750770 [username] => CDZ1 ) [body] => Array ( [0] => Array ( [orderno] => 1 [price] => 15.00 [qty] => 1 ) [1] => Array ( [orderno] => 1 [foodno] => 3 [price] => 9.00 [qty] => 1 ) ) ) Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry ) 

搞不定, 班主帮忙

从这样的数组中都不会取出想要的数据,你的老师该打屁股了

array (  'head' =>   array (    'id' => '4',    'userno' => '12345',    'username' => 'CDZ1',  ),  'body' =>   array (    0 =>     array (      'orderno' => '1',      'price' => '15.00',      'qty' => '1',    ),    1 =>     array (      'orderno' => '1',      'price' => '9.00',      'qty' => '1',    ),  ),)

<?php @header("Content-type: text/html; charset=utf-8");$a='{"head":{"id":"4","userno":"12345","username":"CDZ1"},"body":[{"orderno":"1","price":"15.00","qty":"1"},{"orderno":"1","price":"9.00","qty":"1"}]}';$obj=json_decode($a);echo 'userno:'.$obj->head->userno;echo '<br/>price:'.$obj->body[0]->price;/////或:echo "<br/><br/><br/>";$ary=json_decode($a,true);echo 'userno:'.$ary['head']['userno'];echo '<br/>price:'.$ary['body'][0]['price'];?>

用json_decode()就可以把json的数据格式转换  然后用数组的形式调用了

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php 魔术方法简述Next article:php.ini中有关session