当前位置:Gxlcms > PHP教程 > 主从结构的JSON要如何分拆

主从结构的JSON要如何分拆

时间:2021-07-01 10:21:17 帮助过:54人阅读

主从结构的JSON要怎么分拆
$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.
------解决思路----------------------
从这样的数组中都不会取出想要的数据,你的老师该打屁股了
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',
),
),
)


------解决思路----------------------
@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 '
price:'.$obj->body[0]->price;

/////或:

echo "


";
$ary=json_decode($a,true);
echo 'userno:'.$ary['head']['userno'];
echo '
price:'.$ary['body'][0]['price'];
?>

人气教程排行