phparraysmultidimensional-arrayforeachnested-loops

Access parent level key while inside of a nested loop


How do I reference the key of a multidimensional array? Here is the array:

Array
(
[Nov 18, 2011] => Array
    (
        [C] => 3
        [I] => 1
    )
[Nov 22, 2011] => Array
    (
        [C] => 2
    )
)

and here is the foreach loop:

foreach ($array as $date) { 
    foreach ($date as $k => $v) {         
        // how to I reference the value of $billdate here ?
    }            
} 

It is easy enough to reference the $k and $v inside the inner foreach loop, but how do I reference the date value contained in the outer foreach loop?


Solution

  • Assign the key a value (apparently named $billdate) in the outer foreach loop.

    foreach( $array as $billdate => $date) { 
        foreach( $date as $k => $v) {         
            echo $billdate; // Prints something like Nov 18, 2011
        }            
    }