gpt4 book ai didi

php - 多维数组迭代

转载 作者:行者123 更新时间:2023-12-03 02:16:56 26 4
gpt4 key购买 nike

假设您有以下数组:

$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);

不过,我正在寻找一种使用迭代的方法。

最佳答案

您可以使用 Iterator迭代数组,然后生成所需的输出:

class TranformArrayIterator extends RecursiveIteratorIterator
{
protected function indent()
{
echo str_repeat("\t", $this->getDepth());
return $this;
}
public function beginIteration()
{
echo '<nodes>', PHP_EOL;
}
public function endIteration()
{
echo '</nodes>', PHP_EOL;
}
public function beginChildren()
{
$this->indent()->beginIteration();
}
public function endChildren()
{
$this->indent()->endIteration();
}
public function current()
{
return sprintf('%s<node>%s</node>%s',
str_repeat("\t", $this->getDepth() +1),
parent::current(),
PHP_EOL);
}
}

然后像这样组装它:

$iterator = new TranformArrayIterator(new RecursiveArrayIterator($nodes));

foreach($iterator as $val) {
echo $val;
}

输出

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

要在使用 $key => $val 时清空 $key,请将其添加到 TraverseArrayIterator

public function key()
{
return '';
}

由于您的目标似乎是生成 XML,因此您还可以将 XMLWriter 作为协作者传递给迭代器。这允许对生成的 XML 进行更多控制,并确保输出是有效的 XML:

class TranformArrayIterator extends RecursiveIteratorIterator
{
private $xmlWriter;

public function __construct(
XmlWriter $xmlWriter,
Traversable $iterator,
$mode = RecursiveIteratorIterator::LEAVES_ONLY ,
$flags = 0)
{
$this->xmlWriter = $xmlWriter;
parent::__construct($iterator, $mode, $flags);
}

public function beginIteration()
{
$this->xmlWriter->startDocument('1.0', 'utf-8');
$this->beginChildren();
}
public function endIteration()
{
$this->xmlWriter->endDocument();
}
public function beginChildren()
{
$this->xmlWriter->startElement('nodes');
}
public function endChildren()
{
$this->xmlWriter->endElement();
}
public function current()
{
$this->xmlWriter->writeElement('node', parent::current());
}
}

然后你可以像这样使用它:

$xmlWriter = new XmlWriter;
$xmlWriter->openUri('php://output');
$xmlWriter->setIndent(true);
$xmlWriter->setIndentString("\t");
$iterator = new TranformArrayIterator(
$xmlWriter,
new RecursiveArrayIterator($nodes)
);

foreach 将产生相同的输出(但添加 XML 序言)

关于php - 多维数组迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2207599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com