php中json_decode及foreach使用总结

<?php
$arr=array();
//例子1
$json_str= '{"ret":"OK","questions":{
"1":{"qid":"1","title":"\u95ee\u98981111",
"answers":{
"1":{"cid":"1","title":"A","cont":"\u7b54\u68481-1","iscorrect":"1","qid":"1"},
"2":{"cid":"2","title":"B","cont":"\u7b54\u68481-2","iscorrect":"0","qid":"1"},
"3":{"cid":"3","title":"C","cont":"\u7b54\u68481-3","iscorrect":"0","qid":"1"}
}},
"2":{"qid":"2","title":"\u95ee\u98982222",
"answers":{"5":{
"cid":"5","title":"A","cont":"\u7b54\u68482-1","iscorrect":"0","qid":"2"},
"6":{"cid":"6","title":"B","cont":"\u7b54\u68482-2","iscorrect":"0","qid":"2"},
"7":{"cid":"7","title":"A","cont":"aa","iscorrect":"0","qid":"2"},
"8":{"cid":"8","title":"D","cont":"\u7b54\u68482-4","iscorrect":"0","qid":"2"}}}}}';
// 相关错误反馈
// Notice: Undefined offset: 1
// Notice: Trying to get property of non-object
// Notice: Undefined offset: 0
// Notice: Array to string conversion //json_decode不加参数true,转成的就不是array,而是对象 [questions] => stdClass Object
$arr=json_decode($json_str,true);
// echo "<pre>";print_r($arr);exit; //json_decode不加参数true,下面取值出错: Fatal error: Cannot use object of type stdClass as array in
//通过key:ret取值
echo $arr["ret"];echo "<br/>";
$arr_q=$arr["questions"];
//通过key取值
echo " 1-title:";echo $arr["questions"]["1"]["answers"]["1"]["title"];
echo " 8-title:";echo $arr["questions"]["2"]["answers"]["8"]["title"];
$arr_q1a=$arr["questions"]["1"]["answers"];
$arr_q2a=$arr["questions"]["2"]["answers"];
echo "<br>";echo" q1a:"; var_dump($arr_q1a); $m=count($arr_q1a);echo "m:$m ";
$n=count($arr_q2a);echo "n:$n "; //这个打印就有值 t1:1 t1:2 t1:3
for($i=1;$i<=$m;$i++){
echo " t1:";echo $arr_q1a[$i]['cid'];
}
//这种for会漏值 T2: T2: T2: T2: 按说应该是 5 6 7 8
for($i=1;$i<=$n;$i++){
echo " T2:";echo $arr_q2a[$i]['cid'];
}
//for循环key和value转换就很不方便
foreach ($arr_q2a as $key => $value){
echo "questions 2 : ".$key."->".$value." ";
}
//多维数组,最好用foreach方便
foreach ($arr_q as $key1=>$value1){
echo "<br>"; echo $key1;
foreach ($value1['answers'] as $key2=>$value2){
echo "<br>"; echo $key2."->".$value2;
foreach ($value2 as $key3=>$value3){
echo $key3."->".$value3." ";
}
}
} //例子2
$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
//echo "<pre>";print_r($students);
// for($i=0;$i<count($students);$i++){
// echo "姓名:".$students[$i]['name']."&nbsp;&nbsp;&nbsp;年 龄:".$students[$i]['age']."&nbsp;&nbsp;&nbsp;专 业:".$students[$i]['subject']."<br />";
// }
$students= json_decode($json);//得到的是 object
foreach($students as $obj){
echo "姓名:".$obj->name."年龄:".$obj->age."专业:".$obj->subject."<br/>";
}
?>

总结,php中的多维数组,最好用foreach。

上一篇:POJ 2421 Constructing Roads (最小生成树)


下一篇:请叫我机智-巧用ios朗读kindle图书