duankuixi1930
duankuixi1930
2019-04-14 08:04

如何在ArrayObject类中获取项索引

已采纳

I am implementing a class by inheriting PHP's ArrayObject class. But I don't find how to get the index of the array while iterating. I want to show both key and value

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();

Can anyone help me?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douchi7073 douchi7073 2年前

    I have modified the following line and it's working fine

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

    For more info see here

    点赞 评论 复制链接分享