你好,我有这样的杰森:
[{
"exam_code": "1",
"name": "Name1",
"surname": "Surname1",
"father_name": "Fname1",
"id_number": "211111",
"district_number": "21",
"school_number": "025",
"gender": "F",
"variant": "A",
"grade": "4",
"sector": "A",
"foreign_language": "I",
"answerList": {
"gradeFour": {
"lesson1": ["A", "C", "C", "C", "A", "A", "B", "B", " ", "C", "C", "B", "A", "C", "C", "B", "B", "C", "B", "A"],
"lesson2": ["B", "A", " ", "C", " ", "B", " ", "B", "B", "C", " ", " ", "B", "A", "A", "A", "C", "A", "B", "B"],
"lesson3": ["A", "C", "B", "B", "A", "A", "C", "A", "C", "C"],
"lesson4": ["B", "B", "A", "B", "B"],
"lesson5": ["B", "A", "A", "B", "B"],
"lesson6": ["B", "A", "A", "B", "A", "B", "A", "A", "C", "B"]
}
}
}]
我正在尝试在foreach循环上打印课程答案。
尝试以下代码:
<?php
$msc = microtime(true);
$array = (json_decode($raw_str,true));
foreach($array as $value){
echo $value['id_number'];
echo '<br/>';
foreach($value -> answerList->gradeFour as $val){
echo $val;
}
echo '<br>---------------------------';
echo '<br>';
}
$msc = microtime(true)-$msc;
echo ($msc * 1000) . ' ms'; // in millseconds
?>
但是收到此错误
注意:尝试获取非对象的属性 第50行的G:\ xampp \ htdocs \ siec \ string_test.php注意:试图获取 在线上G:\ xampp \ htdocs \ siec \ string_test.php中非对象的属性 50警告:为in中的foreach()提供了无效的参数 G:\ xampp \ htdocs \ siec \ string_test.php在第50行
答案 0 :(得分:1)
在第二个foreach
循环中,$value
是一个数组。因此,您必须使用方括号[]
而不是->
来使用它:
foreach($value['answerList']['gradeFour'] as $val) {
答案 1 :(得分:0)
您的代码有两个问题:
首先,您必须使用方括号而不是->
第二,您需要使用嵌套循环(两个fors)来打印成绩,因为您有多个课程(另一个数组)的多个成绩(一个数组)。
因此您的完整代码将如下所示:
<script src="vendor/unisharp/laravel-ckeditor/ckeditor.js"></script>
<textarea id="editor1" ></textarea>
<script>
CKEDITOR.replace( 'editor1' );
</script>
答案 2 :(得分:0)
第5行中的问题 您必须将其解码为关联数组 阅读json_decode
检查下面的代码,它将帮助您更加了解
$array = json_decode($raw_str);
foreach($array as $value){
echo $value->id_number;
echo '<br/>';
foreach($value->answerList->gradeFour as $key => $val){
echo $key;
echo "<pre>";
print_r($val);
echo "</pre>";
}
echo '<br>---------------------------';
echo '<br>';
}