php – 多维数组迭代

假设您有以下数组:

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

您将如何将其转换为XML字符串,使其看起来像:

<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>

一种方法是通过递归方法,如:

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

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

    echo "</node>";
}

traverse($nodes);

我正在寻找一种使用迭代的方法.

解决方法:

<?PHP

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

$s = '<node>';
$arr = $nodes;

while(count($arr) > 0)
{
    $n = array_shift($arr);
    if(is_array($n))
    {
        array_unshift($arr, null);
        $arr = array_merge($n, $arr);
        $s .= '<node>';
    }
    elseif(is_null($n))
        $s .= '</node>';
    else
        $s .= '<node>'.$n.'</node>';
}
$s .= '</node>';

echo $s;

?>

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...