在PHP代码中处理JSON 格式的字符串的两种方法:

时间:2023-11-25 14:47:56

总结:

在PHP代码中处理JSON 格式的字符串的两种方法:

方法一:

$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);//得到的是 object

foreach($studentsas $obj){

    echo "姓名:".$obj->name."&nbsp;&nbsp;&nbsp;年 龄:".$obj->age."&nbsp;&nbsp;&nbsp;专 业:".$obj->subject."<br />";
}

方法二:

$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);//得到的是 array

for($i=;$i<count($students);$i++){
echo "姓名:".$students[$i]['name']."&nbsp;&nbsp;&nbsp;年 龄:".$students[$i]['age']."&nbsp;&nbsp;&nbsp;专 业:".$students[$i]['subject']."<br />";
}