php - Show All Data list of multidimensional array Using Foreach Loop
Get the solution ↓↓↓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
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 flagSELF_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> ".$row;
}
}
else{
echo "<br>".$val;
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: illegal string offset
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.