PHP 遍历 ArrayObject
PHP loop through ArrayObject
这是我第一次使用 ArrayObjects,所以我可能 100% 不理解它,但是你能解释一下如何遍历它们吗?
这是我的代码:
$this->plugins = new \ArrayObject(array());
//just for testing...
$this->plugins->plugin1 = "plugin1";
$this->plugins->plugin2 = "plugin2";
$this->plugins->plugin3 = "plugin3";
foreach ($this->plugins as $plugin){
//never reached
}
$this->plugins->count()
returns 0 和 $this->plugins->getIterator()->valid();
returns 也是错误的。
我必须做什么?
你已经走得太远了,但这就是它的工作原理
// You can already have an array like this
$array = array('Buck','Jerry','Tomas');
$arrayObject = new ArrayObject($array);
// Add new element
$arrayObject->append('Tweety');
// We are getting the iterator of the object
$iterator = $arrayObject->getIterator();
// Simple while loop
while ($iterator->valid()) {
echo $iterator->current() . "\n";
$iterator->next();
}
你的代码几乎没问题,只是改变了变量的初始化,所以而不是plugins->plugin1 = "plugin1"
,把所有的东西都放在array("plugin1", ...)
的开头。
所以
$plugins = new ArrayObject(array("plugin1", "plugin2", "plugin3"));
foreach ($plugins as $plugin){
echo $plugin . "<br>";
}
这是我第一次使用 ArrayObjects,所以我可能 100% 不理解它,但是你能解释一下如何遍历它们吗?
这是我的代码:
$this->plugins = new \ArrayObject(array());
//just for testing...
$this->plugins->plugin1 = "plugin1";
$this->plugins->plugin2 = "plugin2";
$this->plugins->plugin3 = "plugin3";
foreach ($this->plugins as $plugin){
//never reached
}
$this->plugins->count()
returns 0 和 $this->plugins->getIterator()->valid();
returns 也是错误的。
我必须做什么?
你已经走得太远了,但这就是它的工作原理
// You can already have an array like this
$array = array('Buck','Jerry','Tomas');
$arrayObject = new ArrayObject($array);
// Add new element
$arrayObject->append('Tweety');
// We are getting the iterator of the object
$iterator = $arrayObject->getIterator();
// Simple while loop
while ($iterator->valid()) {
echo $iterator->current() . "\n";
$iterator->next();
}
你的代码几乎没问题,只是改变了变量的初始化,所以而不是plugins->plugin1 = "plugin1"
,把所有的东西都放在array("plugin1", ...)
的开头。
所以
$plugins = new ArrayObject(array("plugin1", "plugin2", "plugin3"));
foreach ($plugins as $plugin){
echo $plugin . "<br>";
}