我在 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
uj5u.com熱心網友回復:
PHP 以相同的方式處理數字和關聯陣列,列印它們時沒有區別,并且相同的代碼適用于兩者(好吧,除非開始添加花哨的功能......)
所以是的,可以列印關聯陣列。
問題是您的代碼假設資料陣列鍵是數字,通過將 $pointer 屬性初始化為 0(即數值)。可以通過使用 PHP 陣列的內部指標 ($this->items) 或保留陣列鍵的顯式串列來解決這個問題。
版本 1 PHP 具有遍歷陣列的函式,它們被命名為 next()、current()、key() 等,并列在https://www.php.net/manual/en/ref.array.php下。這樣就可以在沒有顯式指標的情況下遍歷陣列:
while(key($arr) !== null) {
echo current($arr)."\n";
next($arr);
}
如果https://www.php.net/manual/en/class.iterator.php下指定的方法在您的 class( implements Iterator)中實作,則可以使用這些函式,如下所示:
class MyIterator implements Iterator {
private $items = [];
private $pointer = 0;
public function __construct($items) {
$this->items = $items;
}
public function current() {
return current($this->items);
}
public function key() {
return key($this->items);
}
// ...
可以看出,它或多或少地輸入了兩次相同的呼叫。但是如果你有一個更復雜的 Iterable 并且添加了其他代碼片段,那么它可能開始值得做這項作業。
版本 2 如果您不想依賴版本 1 中的函式,您仍然可以使用 $this->pointer,但您必須保留陣列鍵的顯式串列:
class MyIterator implements Iterator {
private $items = [];
private $keys = [];
private $pointer = 0;
public function __construct($items) {
$this->items = array_values($items);
$this->keys = array_keys($items);
}
public function current() {
return $this->items[$this->keys[$this->pointer]];
// Alternative version:
return $this->items[$this->key()];
}
// Return the key of the current element
public function key() {
return $this->keys[$this->pointer];
}
// Step the array one element, and then return that value
public function next() {
// Check that we're not moving out of bounds, if so return null
// and follow the next() spec.
$this->pointer;
return $this->items[$this->keys[$this->pointer]];
// Alternative version:
return $this->current();
}
// ...
可以看出,第 2 版創建了另一個陣列“級別”來跟蹤(如果關聯陣列和數值陣列都應該被支持)。但這是可以完成的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/347882.html
下一篇:curl中-u引數是什么意思?
