44

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?

noangel
  • 543
  • 2
  • 6
  • 9
  • Your intial syntax seems ok, but `$value` can be an array itself in the `foreach`. In that case you can't just echo it but you need to loop through it too. – Fanis Hatzidakis Sep 10 '10 at 12:22

6 Answers6

73

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";
        }
    }
}
Alex
  • 6,381
  • 2
  • 24
  • 26
  • I think you may have missed my point, I only want to display a specific nested/sub array, not all of them. – noangel Sep 10 '10 at 12:42
  • @noangel sorry for misunderstanding, see revised post (the last part) after the horizontal rule. This should clarify things. – Alex Sep 10 '10 at 12:50
  • I tried your recursive array output implementation and although it works for first level, my last nested array was simply output on one line – myol Oct 23 '14 at 09:04
6
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;
    }
}
The Codesee
  • 3,628
  • 3
  • 32
  • 71
Pratik Sawant
  • 71
  • 1
  • 2
3

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]).

2ndkauboy
  • 9,136
  • 2
  • 28
  • 62
0

As I understand , all of previous answers , does not make an Array output, In my case : I have a model with parent-children structure (simplified code here):

public function parent(){

    return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}


public function children()
{

    return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}

and if you want to have all of children IDs as an Array , This approach is fine and working for me :

public function allChildren()
{
    $allChildren = [];
    if ($this->has_branch) {

        foreach ($this->children as $child) {

            $subChildren = $child->allChildren();

            if (count($subChildren) == 1) {
                $allChildren  [] = $subChildren[0];
            } else if (count($subChildren) > 1) {
                $allChildren += $subChildren;
            }
        }
    }
    $allChildren  [] = $this->id;//adds self Id to children Id list

    return $allChildren; 
}

the allChildren() returns , all of childrens as a simple Array .

Ali
  • 21
  • 5
0

I had a nested array of values and needed to make sure that none of those values contained &, so I created a recursive function.

function escape($value)
{
    // return result for non-arrays
    if (!is_array($value)) {
        return str_replace('&', '&', $value);
    }

    // here we handle arrays
    foreach ($value as $key => $item) {
        $value[$key] = escape($item);
    }
    return $value;
}

// example usage
$array = ['A' => '&', 'B' => 'Test'];
$result = escape($array);
print_r($result);

// $result: ['A' => '&', 'B' => 'Test'];
domaci_a_nas
  • 167
  • 1
  • 7
0

array( "IT"=> array( array('id'=>888,'First_name'=>'Raahul','Last_name'=>'Pandey'), array('id'=>656,'First_name'=>'Ravi','Last_name'=>'Teja'), array('id'=>998,'First_name'=>'HRX','Last_name'=>'HRITHIK') ), // array( "DS"=> array( array('id'=>87,'First_name'=>'kalia','Last_name'=>'Pandey'), array('id'=>6576,'First_name'=>'Raunk','Last_name'=>'Teja'), array('id'=>9987,'First_name'=>'Krish','Last_name'=>'HRITHIK') ) // ) ) ); // echo ""; // print_r($a); echo ""; print_r($a); ?>

////how to get id in place of index value....

  • in place of index value I want to show id. – user18801450 Apr 14 '22 at 08:18
  • Hi I think you should explain more about what you are doing so that other people can better understand, and also make sure to use the code blocks so that it is more readable. – topsoftwarepro Apr 14 '22 at 10:04
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 14 '22 at 10:05