![](/img/trans.png)
[英]PHP: how to get the same index for the same values in an associative array?
[英]How to get the index of an associative array in PHP?
以下JSON字符串显示了所提交的两个问题的正确性,我想知道两个问题的ID,即“ submission”,“ question1”和“ question2”内的关联数组的索引。 我应该怎么做? 谢谢!
<?php
$test =
'{
"event_source": "server",
"event_type": "problem_check",
"submission": {
"question1":{
"correct":false
}
"question2":{
"correct":true
}
}
}';
$jarray = json_decode($test, true);
1.You JSON数据有一些缺失,
和""
(检查我的正确格式输出链接)
2.如果要显示每个问题提交结果,请使用foreach()
。
$jarray = json_decode($test, true);
foreach($jarray['submission'] as $key=>$value){
echo $key. ' answer is '.$value['correct'].PHP_EOL;
}
输出:-https: //3v4l.org/T3sh4或https://3v4l.org/3lUNF
3. 如果只需要键,请执行以下操作:
$questionIds = array_keys($jarray['submission']);
输出: -https : //3v4l.org/f0oHq
参考文献: -
一个相当简单的方法,但是应该可以解决问题:
$i = 0;
foreach($jarray['submission'] as $key => $val) {
echo $key " is the index ". $i;
$i++;
}
您可以使用array_keys()
$newArray = array_keys($test);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.