【发布时间】:2021-12-18 17:25:52
【问题描述】:
我在 w3schools 看到了一个例子:
<?php
// Create an Iterator
class MyIterator implements Iterator {
private $items = [];
private $pointer = 0;
public function __construct($items) {
// array_values() makes sure that the keys are numbers
$this->items = array_values($items);
}
public function current() {
return $this->items[$this->pointer];
}
public function key() {
return $this->pointer;
}
public function next() {
$this->pointer++;
}
public function rewind() {
$this->pointer = 0;
}
public function valid() {
// count() indicates how many items are in the list
return $this->pointer < count($this->items);
}
}
// A function that uses iterables
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}
// Use the iterator as an iterable
$iterator = new MyIterator(["a", "b", "c"]);
printIterable($iterator);
?>
如果当前方法是关联数组而不是数字,则可以循环数组。如果是,我该怎么做?示例我们可以这样做:
function printIterable(iterable $myIterable) {
foreach($myIterable as $item => $value) {
echo "$item - $value";
}
}
// Use the iterator as an iterable
$iterator = new MyIterator(["a"=>1, "b"=>2, "c"=>3]);
printIterable($iterator);
当我尝试时。它打印这个:0 - 11 - 22 - 3
【问题讨论】:
-
输出看起来不错,你想要它是什么?不过,您可能希望在 printIterable() 中的每一行之后添加一个行分隔符,这样会更容易阅读:)。
-
@TorbjörnStabo 它正在将数组打印为数字并且它是关联的,是否可以打印为关联只想知道
-
这就是我要说的:)。
$arr = ['name' => 'Eric']; foreach($arr as $k => $v) { echo "$k: $v\n"; }查看php.net/next 的初学者,然后查看该页面上的“另请参阅”部分。 -
我会把它留给内部 PHP 数组指针,然后使用我之前提到的数组函数。
-
"如果我没有将 array_values() 函数放在构造函数中,它不会打印数组,如果我把它打印为数字的关联数组“就像我之前说的,如果你将该array_values() 调用添加到构造函数没有 没有关联数组。 Array_values() 返回关联数组的数字“版本”,然后保存在 $this->items 中。