PHP 关联数组获取数组ID
PHP associative Array get Array Id
嗨,我无法理解这个问题,我有以下数组:
Array
(
[questions] => Array
(
[585] => Array
(
[correct] => 1
[mark] => 1
[type] => single_choice
[answered] => 1
)
[596] => Array
(
[correct] =>
[mark] => 0
[type] => true_or_false
[answered] => 1
)
[595] => Array
(
[correct] => 1
[mark] => 1
[type] => single_choice
[answered] => 1
)
)
)
我正在尝试在 foreach 语句中获取数组编号,这是我的代码,它适用于除数字之外的所有其他内容,我只需要在 foreach 外观中获取 585,596 ir 595。
<?php
/// $quiz_res is the array
foreach($quiz_res['questions'] as $result) {
echo key($result); //// DOES NOT WORK
##### I need to get the number here eg 585 ???
echo $result['correct']; /// this works
echo $result['mark']; /// this works
echo $result['type']; /// this works
echo $result['answered']; /// this works
}
?>
这也不重要,但这与 learnpress 测验的结果有关,如果有人熟悉的话。
任何帮助或指点将不胜感激
您必须在 foreach 调用中命名索引:
foreach($quiz_res['questions'] as $id => $result) {
echo $id; // 585
嗨,我无法理解这个问题,我有以下数组:
Array
(
[questions] => Array
(
[585] => Array
(
[correct] => 1
[mark] => 1
[type] => single_choice
[answered] => 1
)
[596] => Array
(
[correct] =>
[mark] => 0
[type] => true_or_false
[answered] => 1
)
[595] => Array
(
[correct] => 1
[mark] => 1
[type] => single_choice
[answered] => 1
)
)
)
我正在尝试在 foreach 语句中获取数组编号,这是我的代码,它适用于除数字之外的所有其他内容,我只需要在 foreach 外观中获取 585,596 ir 595。
<?php
/// $quiz_res is the array
foreach($quiz_res['questions'] as $result) {
echo key($result); //// DOES NOT WORK
##### I need to get the number here eg 585 ???
echo $result['correct']; /// this works
echo $result['mark']; /// this works
echo $result['type']; /// this works
echo $result['answered']; /// this works
}
?>
这也不重要,但这与 learnpress 测验的结果有关,如果有人熟悉的话。
任何帮助或指点将不胜感激
您必须在 foreach 调用中命名索引:
foreach($quiz_res['questions'] as $id => $result) {
echo $id; // 585