Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array that looks like this in var_dump.

array (size=3)
  0 => 
    array (size=2)
      0 => 
        array (size=1)
          '08:40:00' => string '8:40 am' (length=7)
      1 => 
        array (size=1)
          '09:00:00' => string '9:00 am' (length=7)
  1 => 
    array (size=5)
      0 => 
        array (size=1)
          '12:00:00' => string '12:00 pm' (length=8)
      1 => 
        array (size=1)
          '12:20:00' => string '12:20 pm' (length=8)
      2 => 
        array (size=1)
          '12:40:00' => string '12:40 pm' (length=8)
      3 => 
        array (size=1)
          '13:00:00' => string '1:00 pm' (length=7)
      4 => 
        array (size=1)
          '13:20:00' => string '1:20 pm' (length=7)

Whats the best way to loop through this array to access the 2nd level elements (the clock times), WITHOUT assuming the sizeof the main array (currently 2).

Yes i'm seeking code assistance, but most examples on google are for arrays with string indexes like testarray['breakfasttimes'] and testarray['lunchtimes'].

share|improve this question
1  
foreach inside foreach? –  asprin May 5 at 10:13
    
nested foreach loops –  Mark Baker May 5 at 10:13
    
The current size of the main array is 3, BTW, not 2... also: if the keys are strings, then you access them through strings, if they are ints, then you access them through strings, but the result is the same: $array['foo'] access the foo key, whereas $array[0] accesses the value of the 0 index... –  Elias Van Ootegem May 5 at 10:25

1 Answer 1

You would need a recursive function like this one

function show_branch($branches, $level = 0, $index = null) {
    if (!is_array($branches)/* and $level == 2 */) {
        echo $index.' - '.$branches.' (level: '.$level.')';
        return;
    }
    $level++;
    foreach ($branches as $branch) {
        show_branch($branch, $level, $index);
    }
}

show_branch($tree);

This function browses your tree until the non array branches.
You can also add a condition if you want to see only the level 2.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.