PHP foreach with Nested Array?

0 votes
asked Sep 10, 2010 by noangel

I have a nested array in which I want to display a subset of results. For example, on the array below I want to loop through all the values in nested array[1].

Array
(
  [0] => Array
    (
      [0] => one
      [1] => Array
        (
          [0] => 1
          [1] => 2
          [2] => 3
        )
    )

  [1] => Array
    (
      [0] => two
      [1] => Array
        (
          [0] => 4
          [1] => 5
          [2] => 6
        )
    )

  [2] => Array
    (
      [0] => three
      [1] => Array
        (
          [0] => 7
          [1] => 8
          [2] => 9
        )
    )
)

I was trying to use the foreach function but I cannot seem to get this to work. This was my original syntax (though I realise it is wrong).

$tmpArray = array(array("one",array(1,2,3)),array("two",array(4,5,6)),array("three",array(7,8,9)));

foreach ($tmpArray[1] as $value) {
  echo $value;
}

I was trying to avoid a variable compare on whether the key is the same as the key I want to search, i.e.

foreach ($tmpArray as $key => $value) {
  if ($key == 1) {
    echo $value;
  }
}

Any ideas?

4 Answers

0 votes
answered Sep 10, 2010 by 2ndkauboy

Both syntaxes are correct. But the result would be Array. You probably want to do something like this:

foreach ($tmpArray[1] as $value) {
  echo $value[0];
  foreach($value[1] as $val){
    echo $val;
  }
}

This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).

0 votes
answered Sep 10, 2010 by alex

If you know the number of levels in nested arrays you can simply do nested loops. Like so:

//  Scan through outer loop
foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

if you do not know the depth of array you need to use recursion. See example below:

//  Multi-dementional Source Array
$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(
            7,
            8,
            array("four", 9, 10)
    ))
);

//  Output array
displayArrayRecursively($tmpArray);

/**
 * Recursive function to display members of array with indentation
 *
 * @param array $arr Array to process
 * @param string $indent indentation string
 */
function displayArrayRecursively($arr, $indent='') {
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                //
                displayArrayRecursively($value, $indent . '--');
            } else {
                //  Output
                echo "$indent $value \n";
            }
        }
    }
}

The code below with display only nested array with values for your specific case (3rd level only)

$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(7, 8, 9))
);

//  Scan through outer loop
foreach ($tmpArray as $inner) {

    //  Check type
    if (is_array($inner)) {
        //  Scan through inner loop
        foreach ($inner[1] as $value) {
           echo "$value \n";
        }
    }
}
0 votes
answered Sep 18, 2013 by pratik-sawant
foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

Perfect worked for me.... try this

0 votes
answered Sep 15, 2017 by mario-caseres

How about this data:

[0] => Array (
    [item] => null
    [count] => 0
    [child] => Array (
        [1] => Array (
            [item] => 1
            [count] => 6
            [child] => Array (
                [5] => Array (
                    [item] => 5
                    [count] => 3
                    [child] => Array (
                        [4] => Array (
                            [item] => 4
                            [count] => 1
                            )
                        )
                    )
                [3] => Array (
                    [item] => 3
                    [count] => 2
                    [child] => Array (
                        [4] => Array (
                            [item] => 4
                            [count] => 1
                            )
                        )
                    )
                )
            )
        [3] => Array (
            [item] => 3
            [count] => 1
            [child] => Array (
                [4] => Array (
                    [item] => 4
                    [count] => 1
                    )
                )
            )
        )
    )

Can you get all the pathways? Data looks like a binary tree. Need somehelp

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...