user1145238 user1145238 - 6 months ago 15
PHP Question

foreach top level multidimentional array then foreach inside

with an array like below..

Array
(
[headerA] => Array
(
[a1] => content1
[a2] => content2
[a3] => content3
)

[headerB] => Array
(
[a4] => content4
[a5] => content5
[a6] => content6
[a7] => content7

)

[headerC] => Array
(
[a8] => content8
[a9] => content9
[a10] => content10

)
)


Is there a better way to acheive the following, effectively a nested foreach. where this code foreach's through the high level array, then foreach inside that to process its contents, with an output like below?

foreach ($array as $k=>$v){
echo $k."<br/>";
foreach ($v as $k1=>$v1){
echo $k1." ".$v1."<br/>";
}
}


Would output..

headerA
a1 content1
a2 content2
a3 content3

headerB
a4 content4
a5 content5
a6 content6
a7 content7

headerC
a8 content8
a9 content9
a10 content10

Answer

An alternative way to nested foreach is to use a recursive function.

I say "alternative" because the concept of "better" depends on the context where you use it. The main advantage of recursive method is, of course, that there's no limit on the number of level of the array: in linear mode you need one foreach for each array's dimension (3-dimensions array => 3 foreach); in recursive mode the code remain the same no matter the number of dimensions.

Here an example:

function recursive_print ($array)
{
    echo "<br />\n";
    foreach ($array as $k => $v)
    {
        echo $k;

        if (is_array ($v) || is_object ($v)) recursive_print ($v);
        else echo ' ' . $v;

        echo "<br />\n";
    }
}

Can be also useful to add a $level parameter, to know the level of recursion you are in:

function recursive_print ($array, $level = 0)
{
    if ($level > 0) echo "<br />\n";
    foreach ($array as $k => $v)
    {
        echo $k;

        if (is_array ($v) || is_object ($v)) recursive_print ($v, $level + 1);
        else echo ' ' . $v;

        echo "<br />\n";
    }
}

In both cases, the call to the function simply is:

recursive_print ($array);
Comments