PHP associative Array get Array Id

812 Views Asked by At

Hi I cant get my head around this one I have the following array :

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
            )

   )

)

I am trying to get the arrays number in a foreach statement here is my code , it works for everything else apart from the numbers I just need to get either 585,596 ir 595 in the foreach look .

          <?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 
                }
           ?>

Also it shouldnt matter but this is relating to the results of a learnpress quiz if any one is familiar with them.

Any help or pointers would be greatly appreciated

1

There are 1 best solutions below

1
On BEST ANSWER

You have to name the index in the foreach call:

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

echo $id; // 585