Reputation: 1047
I don't have a problem, but i'm looking for any other maybe better or faster solution. I have array with two keys ALL and ART:
$myData = Array (
[ALL] => Array (
[0] => Array (
[ID_COUNTRY] => 23
[DELIVERY_DAYS] => 23
[AMOUNT] => 23
)
[1] => Array (
[ID_COUNTRY] => 30
[DELIVERY_DAYS] => 30
[AMOUNT] => 30
)
)
[ART] => Array (
[0] => Array (
[ID_COUNTRY] => 10
[DELIVERY_DAYS] => 10
[AMOUNT] => 10
)
[1] => Array (
[ID_COUNTRY] => 2
[DELIVERY_DAYS] => 20
[AMOUNT] => 20
)
)
)
And have 2 foreach loops to check the values
<?php
foreach ($myData as $key1=>$key2) {
foreach ($key2 as $key=>$data) {
...
}
}
?>
Is possible to do something like this or is the only solution to use two foreach loops without any additional libraries.
<?php
foreach($myData as $key1=>$key2=>$value) {
echo $key1; // [ALL] or [ART]
echo $key2; // [ALL][$key2] or [ART][$key2];
}
?>
Upvotes: 0
Views: 180
Reputation: 22783
Perhaps not exactly what you are looking for; I still wanted to notify you of it though. You can recursively loop through a multidimensional array, using a RecursiveArrayIterator
in combination with a RecursiveIteratorIterator
:
$rii = new RecursiveIteratorIterator( new RecursiveArrayIterator( $myData ), RecursiveIteratorIterator::SELF_FIRST );
foreach( $rii as $key => $value )
{
echo $key;
// you can keep track of the current depth with:
$depth = $rii->getDepth();
}
Upvotes: 0
Reputation: 8448
It's not possible. But you could do it as
<?php
foreach ($myData as $key1=>$key2) {
foreach ($key2 as $key=>$data) {
echo $key1;
echo $key2;
}
}
?>
Upvotes: 1
Reputation: 64399
If you want to loop over your multi-dimensional array you need your provided code:
foreach ($myData as $key1=>$key2) {
foreach ($key2 as $key=>$data) {
...
}
}
No way around it without using something that would in the end do this too. There is no speed to be gained here. And if there is it would be a micro-optimization that you should ignore :)
Upvotes: 3