多维数组迭代 [英] Multidimensional array iteration

查看:106
本文介绍了多维数组迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有以下数组:

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

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

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.

推荐答案

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

?>

这篇关于多维数组迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆