Reputation: 195
The following JSON string shows the correctness of two questions submitted and I want to know the IDs of the two questions, namely the indices of the associatve arrays within "submission", "question1" and "question2". How am I supposed to do that? Thanks!
<?php
$test =
'{
"event_source": "server",
"event_type": "problem_check",
"submission": {
"question1":{
"correct":false
}
"question2":{
"correct":true
}
}
}';
$jarray = json_decode($test, true);
Upvotes: 2
Views: 64
Reputation: 72289
1.You json data have some missing ,
and ""
(check my output links for correct format)
2.Use foreach()
if you want to show each question submission result.
$jarray = json_decode($test, true);
foreach($jarray['submission'] as $key=>$value){
echo $key. ' answer is '.$value['correct'].PHP_EOL;
}
Output:- https://3v4l.org/T3sh4 OR https://3v4l.org/3lUNF
3.If you want only keys then do:-
$questionIds = array_keys($jarray['submission']);
Output:- https://3v4l.org/f0oHq
References:-
Upvotes: 3
Reputation: 1727
A rather simple approach but it should do the trick:
$i = 0;
foreach($jarray['submission'] as $key => $val) {
echo $key " is the index ". $i;
$i++;
}
Upvotes: 2