I have array like this:
$array = [
'Category 1',
'Category 2',
[
[
'SubCategory 1',
'SubCategory 2'
],
[
'SubCategory 3',
'SubCategory 4',
[
[
'SubSubCategory 1',
'SubSubCategory 2'
]
]
],
[
'SubCategory 4',
'SubCategory 5',
[
[
'SubSubCategory 3',
'SubSubCategory 4'
]
]
]
]
];
And i try do recursion:
function recursive($array)
{
foreach($array as $key => $val) {
if(is_array($val)) {
recursive($val);
}
echo $val;
}
}
It throws an notice "Notice: Array to string conversion" because
[2] => array(
[0] => array(..)
[1] => array(..)
..
);
And also echo Array
In this case, when the array has such a layout. How can I avoid that notice?
Cœur
38.9k25 gold badges206 silver badges281 bronze badges
asked Jul 16, 2018 at 9:47
user9076455user9076455
1 Answer 1
You only want to echo
the value if it is not an array, so just add an else
.
function recursive($array)
{
foreach($array as $key => $val) {
if(is_array($val)) {
recursive($val);
} else {
echo $val;
}
}
}
answered Jul 16, 2018 at 9:50
lang-php
'category 2' => array(
...this is not true in your code above. "Category 2" in your array is a simple string at index 1 of the array. Then index 2 is an array, separately. Are you trying to create an associative array?