-3

How can I iterate over this array? Syntax of loop

$t = array(
  'grn_id' => array(
    'status_id' => array(1, 2, 3, 4)
  )
)
6
  • 2
    What output are you expecting from this? And also show us the full array. Commented Jul 5, 2017 at 9:09
  • nested foreach loops? Commented Jul 5, 2017 at 9:10
  • ouptut = 1 2 3 4 Commented Jul 5, 2017 at 9:10
  • 5
    have you try anything? Commented Jul 5, 2017 at 9:11
  • 1
    Possible duplicate of Fastest way to iterate array in PHP Commented Jul 5, 2017 at 9:15

2 Answers 2

0

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;
  }
} 
Sign up to request clarification or add additional context in comments.

10 Comments

is there a possibilty if i can access or output all 'status_id' keys (if i put many keys like 'status_id'), can output them?
You mean you have one 'status_id' and one 'status_id2'?
@AyushKumar That's what my code does... What next? I don't understand.
@Praveen your code outputs 1 2 3 4, but if i want to print 'status_id'...
@Andreas I'll try to use the code from your comment and update my answer.
|
0

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

1 Comment

Link only answer are usually not liked. Copy the part you want to link to here instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.