PHP关联数组获取数组ID

时间:2019-04-22 10:13:53

标签: php wordpress learnpress

嗨,我无法理解,我有以下数组:

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或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测验的结果有关。

任何帮助或指针将不胜感激

1 个答案:

答案 0 :(得分:4)

您必须在foreach调用中命名索引:

foreach($quiz_res['questions'] as $id => $result) {

echo $id; // 585