Asked  7 Months ago    Answers:  5   Viewed   82 times

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?

 Answers

24

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";
        }
    }
}
Wednesday, March 31, 2021
 
vuliad
answered 7 Months ago
40

You have to get the indexes to access the values in the other array:

foreach($_POST['experiences'] as $idx => $experience) {
    $sql = "INSERT INTO experiences (number, experience, years)
            VALUES ({$idx}, {$experience}, {$_POST['years'][$idx]}");
    // execute query, etc
}

This will work, but you probably shouldn't do it this way because it leaves you open for SQL injections. A better way to do this would be by sanitizing your inputs (eg: mysql_reaL_escape_string or its mysqli equivalent)

The best way to go would be using prepared statements:

$stmt = $dbh->prepare("INSERT INTO experiences (number, experience, years) 
                       VALUES (?, ?, ?)");

foreach($_POST['experiences'] as $idx => $experience) {
    // pass values and execute
    $stmt->execute(array($idx, $experience, $_POST['years'][$idx]));
}
Wednesday, March 31, 2021
 
tplaner
answered 7 Months ago
41

You can use this code

<html>
    <style>
    </style>
    <body>
        <?php

$v_company= array(
    'ABC'=>
        array('Kuching'=>array('Michael', 'Jenny'), 
             'Sibu'=>array('Sally', 'Muhammad', 'Mutu')
                ),
    'XYZ'=>array('Kuching'=>array('Lucy', 'Abdullah'), 
                'Sibu'=>array('John', 'Alicia')
    )
);





?>
<table>

<tr><th>Company's Name</th>
    <th>Branch</th>
    <th>Staff's Name</th>
</tr>
<?php
$company = '';
$branch = '';
$staff = '';
foreach($v_company as $v_company_name=>$v_company_info){
    foreach($v_company_info as $v_branch=>$v_staffs){
        foreach($v_staffs as $v_staff){
              echo "<tr>";
                  echo "<td>";
                        if($company == '' || $company != $v_company_name){
                            $company = $v_company_name;
                            echo "$v_company_name <br>";
                        }

                  echo "</td>";
                  echo "<td>";
                        if($branch != $v_branch){
                            $branch = $v_branch;
                            echo "$v_branch <br>";
                        }

                  echo "</td>";
                  echo "<td>";
                      echo "$v_staff <br/>";
                  echo "</td>";
              echo "</tr>";  
         }
    }    
}
?>
</table>
</body>
</html>

You can copy paste if you want. Happy coding

Saturday, May 29, 2021
 
Jubair
answered 5 Months ago
52

That's a perfect job for Iterators:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key => $value) {
    echo "$key => $valuen";
}

See Introduction to SPL Iterators and Live Demo on codepad

EDIT: the alternative would be array_walk_recursive as show in Finbarr's answer below

Thursday, July 22, 2021
 
rlanvin
answered 3 Months ago
52

You need to iterate the elements from the inside array, like this:

foreach($resultArray as $row => $innerArray){
  foreach($innerArray as $innerRow => $value){
    echo $value . "<br/>";
  }
}
Wednesday, August 4, 2021
 
Cam1989
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :