Reputation: 101
Hello I have Json like this:
[{
"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"]
}
}
}]
I am trying to print out lessons answers on foreach loop.
tried below code:
<?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
?>
But getting this error
Notice: Trying to get property of non-object in G:\xampp\htdocs\siec\string_test.php on line 50 Notice: Trying to get property of non-object in G:\xampp\htdocs\siec\string_test.php on line 50 Warning: Invalid argument supplied for foreach() in G:\xampp\htdocs\siec\string_test.php on line 50
Upvotes: 2
Views: 2198
Reputation: 158
Your problem in line 5 you must decode it as associative arrays read json_decode
check the code below, it will help you to more understand
$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>';
}
Upvotes: 0
Reputation: 3653
There are two problems to your code:
First, you have to use brackets instead of ->
Second, you need to use nested loop (two fors) to print the grades, since you have multiple grades (an array) for multiple lessons (another array).
So your complete code will be like this:
$msc = microtime(true);
$array = (json_decode($raw_str,true));
foreach($array as $value){
echo $value['id_number'];
echo '<br/>';
foreach($value['answerList']['gradeFour'] as $course){
foreach($course as $val){
echo $val;
}
}
echo '<br>---------------------------';
echo '<br>';
}
Upvotes: 0
Reputation: 423
In your second foreach
loop, $value
is an array. So you have to use it with brackets []
not ->
:
foreach($value['answerList']['gradeFour'] as $val) {
Upvotes: 1