Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 733
DanielAttard Avatar asked Jun 21 '26 18:06

DanielAttard


2 Answers

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
    }            
} 
like image 176
nickb Avatar answered Jun 24 '26 08:06

nickb


Assuming $billdate is the key of each top-level array:

foreach ($array as $billdate => $date) {
    foreach ($date as $k => $v) {
        var_dump($billdate, $k, $v);
    }
}
like image 36
Ross Avatar answered Jun 24 '26 09:06

Ross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!