In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
这篇文章主要为大家展示了"php中如何将json转换成对象",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"php中如何将json转换成对象"这篇文章吧。
php json转换成对象的方法:1、用json_decode对JSON格式的字符串进行编码;2、通过"foreach($students as $obj){...}"方式访问即可。
本文操作环境:Windows7系统、PHP7.1版,Dell G3电脑
php json字符串转为数组或对象
从网上查到的方法是 用get_object_vars 把类类型转换成数组 然后在用foreach 遍历即可
$array = get_object_vars($test);$json= '[{"id":"1","name":"\u5f20\u96ea\u6885","age":"27","subject":"\u8ba1\u7b97\u673a\u79d1\u5b66\u4e0e\u6280\u672f"},{"id":"2","name":"\u5f20\u6c9b\u9716","age":"21","subject":"\u8f6f\u4ef6\u5de5\u7a0b"}]';
首先要用 json_decode 对 JSON 格式的字符串进行编码,
$students = json_decode($json);
直接在PHP文件用$students :
for($i=0;$i object(stdClass)#2 (4) { ["id"]=> string(1)"1" ["name"]=> string(9)"张雪梅" ["age"]=> string(2)"27" object(stdClass)#3 (4) { 这个就说明转换的json字符串转为对象而非数组,请看下面的红色背景字 ["subject"]=>string(24) "计算机科学与技术" } [1]=> ["id"]=> string(1)"2" ["name"]=> string(9)"张沛霖" ["age"]=> string(2)"21" ["subject"]=> string(12) "软件工程" } }
可见,返回的结果是 object 而非 array。应以对象形式访问:
foreach($students as $obj){ echo "姓名:".$obj->name."年龄:".$obj->age."专业:".$obj->subject.""; }
输出结果为:
姓名:张雪梅 年龄:27 专业:计算机科学与技术
姓名:张沛霖 年龄:21 专业:软件工程
mixedjson_decode ( string$json [, bool$assoc ] )
说明:接受一个 JSON 格式的字符串并且把它转换为 PHP 变量。
json_decode 可接收两个参数:
json:待解码的jsonstring 格式的字符串。
assoc:当该参数为 TRUE 时,将返回 array 而非 object 。
$students = json_decode($json,true);
这时打印一下 $students :
var_dump($students);
输出:
array(2) { [0]=> array(4) { ["id"]=> string(1)"1" ["name"]=> string(9)"张雪梅" ["age"]=> string(2)"27" ["subject"]=>string(24) "计算机科学与技术" } [1]=> array(4) { ["id"]=> string(1)"2" ["name"]=> string(9)"张沛霖" ["age"]=> string(2)"21" ["subject"]=>string(12) "软件工程" } }
这时,$students 就是个数组了,可以直接用:
for($i=0;$iname." 年 龄:".$obj->age." 专 业:".$obj->subject."";}
方法二:
$json= '[{"id":"1","name":"\u5f20\u96ea\u6885","age":"27","subject":"\u8ba1\u7b97\u673a\u79d1\u5b66\u4e0e\u6280\u672f"},{"id":"2","name":"\u5f20\u6c9b\u9716","age":"21","subject":"\u8f6f\u4ef6\u5de5\u7a0b"}]';$students= json_decode($json, true);//得到的是 arrayfor($i=0;$i
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.