How can I iterate over this array? Syntax of loop
$t = array(
'grn_id' => array(
'status_id' => array(1, 2, 3, 4)
)
)
In simple words, if you want that, you can get:
foreach ($t["grn_id"]["status_id"] as $statusId)
echo $statusId;
You will get 1, 2, 3, 4 in each iteration.
foreach ($t["grn_id"] as $grn) {
foreach ($grn as $statusId) {
echo $statusId;
}
}
Perhaps a recursive iterator is what you're looking for ?
You can check the example given :
<?php
$myArray = array(
0 => 'a',
1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
2 => 'b',
3 => array('subA','subB','subC'),
4 => 'c'
);
$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, 'traverseStructure', array($iterator));
function traverseStructure($iterator) {
while ( $iterator -> valid() ) {
if ( $iterator -> hasChildren() ) {
traverseStructure($iterator -> getChildren());
}
else {
echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;
}
$iterator -> next();
}
}
?>
And the output is :
0 : a
0 : subA
1 : subB
0 : subsubA
1 : subsubB
0 : deepA
1 : deepB
2 : b
0 : subA
1 : subB
2 : subC
4 : c
foreachloops?