主从结构的JSON要怎么分拆
程序员文章站
2024-01-14 12:19:16
...
$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] => 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 )
搞不定, 班主帮忙
这样的一段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', ), ),)
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'];?>
用json_decode()就可以把json的数据格式转换 然后用数组的形式调用了
上一篇: 小议sqlserver数据库主键选取策略
下一篇: php操作字符串转换成数组
推荐阅读