如何在ArrayObject类中获取项索引

问题描述 投票:0回答:1

我通过继承PHP的ArrayObject类来实现一个类。但我没有找到如何在迭代时获取数组的索引。我想展示关键和价值

class TestArrayObject extends ArrayObject {
    public function displayAsTable() {
        $iterator = $this->getIterator();
        // Table
        echo '<table border="1">';
        echo '<tr>';
        echo '<th>Keys</th><th>Values</th>';
        echo '</tr>';
        while ($iterator->valid()) {
            echo '<tr>';
            echo '<td>'.$iterator->current().'</td><td>'.$iterator->current().'</td>';
            echo '</tr>';
            $iterator->next();
        }
        echo '</table>';
    }
}

$arrFruits = array('Apple','Banana', 'Mango');
$objArr = new TestArrayObject($arrFruits);
$objArr->displayAsTable();

谁能帮我?

php arrayobject
1个回答
0
投票

我修改了以下行,它工作正常

'<td>'.$iterator->key().'</td><td>'.$iterator->current().'</td>'

有关更多信息see here

© www.soinside.com 2019 - 2024. All rights reserved.