php - Show All Data list of multidimensional array Using Foreach Loop ← (PHP)

Solution:

This is best achieved with a recursive function so that you can deal with any level of nested arrays:

function display_list($array) {
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            echo "$k\n";
            display_list($v);
        }
        else {
            echo "$v\n";
        }
    }
}
display_list($data);

Output:

data_1
data_2
data_3 
data_4 
data_5 
data_5_1 
data_5_2

Demo on 3v4l.org

Answer



Solution:

You could use iterators:

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $item)
  echo "$item<br>", PHP_EOL;

As asked in comments, if you want either the key or value depending on type, you can use the flag SELF_FIRST and the ternary operator:

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($data), RecursiveIteratorIterator::SELF_FIRST) as $key => $item)
  echo (is_scalar($item) ? $item : $key) . '<br>', PHP_EOL;

Answer



Solution:

foreach ($data as $val) {
    if(is_array($val)){
        foreach ($val as $row) {
            echo "<br>&nbsp;&nbsp;&nbsp;&nbsp;".$row;
        }
    }
    else{ 
         echo "<br>".$val;
    }
}

Source