Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


multidimensional array iteration


multidimensional array iteration  using -'php,recursion,multidimensional-array,iteration'

Say you have the following array:

$nodes = array(
    "parent node",
    "parent node",
    array(
        "child node",
        "child node",
        array(
            "grand child node",
            "grand child node")));


How would you go about transforming it to an XML string so that it looks like:

<node>
    <node>parent node</node>
    <node>parent node</node>
    <node>
        <node>child node</node>
        <node>child node</node>
        <node>
            <node>grand child node</node>
            <node>grand child node</node>
        </node>
    </node>
</node>


One way to do it would be through a recursive method like:

function traverse($nodes)
{
    echo "<node>";

    foreach($nodes as $node)
    {
        if(is_array($node))
        {
            traverse($node);
        }
        else
        {
            echo "<node>$node</node>";
        }
    }

    echo "</node>";
}

traverse($nodes);


I'm looking for an approach that uses iteration, though.
    

asked Oct 19, 2015 by rajeshujade
0 votes
4 views



Related Hot Questions



Government Jobs Opening


...