gpt4 book ai didi

php - 如何在 PHP 中使用 ArrayIterator append 带有键的元素?

转载 作者:搜寻专家 更新时间:2023-10-31 21:26:47 25 4
gpt4 key购买 nike

ArrayIterator 的 PHP 站点上没有文档超出基本参数引用的对象,所以我什至不确定这是可能的。

我理解 ArrayIterator 的概念从基本意义上讲,就像这个例子:

$rows = new ArrayIterator(array('a', 'b', 'c'));
foreach ($rows as $row) {
echo "<p>This is row {$a}.</p>";
}

在我的例子中,行数组有点复杂(尽管为了这个例子仍然被简化了)......

$rows = array(
'a' => NULL,
'b' => array('d' => NULL, 'e' => NULL, 'f' => NULL),
'c' => NULL
);
$rows = new ArrayIterator($rows);

想法是'b'在这种情况下,有许多子元素应该被解析为父元素,在末尾 (不需要按顺序处理)其余父元素(a,b ,c).

通常我会使用...

foreach ($child as $c) {
$rows->append($c);
}

但在这种情况下 $child是一个带有我要维护的键的数组...

foreach ($child as $key => $c) {
$rows->append($c); // but what about $key???
}

我不想在末尾添加一个数组作为元素,我想将添加到父列表,这样我们就结束了与....

$rows = array(
'a' => ...,
'b' => ...,
'c' => ...,
'd' => ...,
'e' => ...,
'f' => ...
);

问题:是否可以在 foreach 循环中使用键将元素 append 到当前迭代数组?

最佳答案

ArrayIterator 实现了ArrayAccess 接口(interface)。这意味着 offsetset可用,您可以为指定的偏移量赋值。

foreach 所说文档:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

但在这种情况下不需要。

$rows = array(
'a' => 1,
'b' => array('d' => 3, 'e' => 4, 'f' => 5),
'c' => 2
);

$rows = new ArrayIterator($rows);

foreach ($rows as $key => $row) {
if (is_array($row)) {
foreach ($row as $key => $c) {
$rows[$key] = $c;
}

// skip this
continue;
}

echo $key, " ", $row, "\n";
}

这个打印:

a 1
c 2
d 3
e 4
f 5

Demo .

关于php - 如何在 PHP 中使用 ArrayIterator append 带有键的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34954971/

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