ArrayIterator迭代器遍历数组

来源:互联网 发布:软件销售工作好么 编辑:程序博客网 时间:2024/05/22 08:07

代码

<?phpnamespace app\index\controller;use ArrayObject;//引入迭代器class Index{    public function index()    {        $fruits = array(            "apple" => 'apple value',//position =0            "orange" => 'orange value',//position =1            "grape" => 'grape value',            "plum" => 'plum value',        );        dump($fruits);        echo '------------------普通数组遍历-----------------'."<br/>";        foreach ($fruits as $key => $value) {            echo $key.":".$value."<br/>";        }        echo '------------------使用ArrayIterator迭代器遍历数组(foreach)-----------------'."<br/>";        $obj = new ArrayObject($fruits);//创建数组对象        $it = $obj->getIterator();//获取迭代器        foreach ($it as $key => $value) {            echo $key.":".$value."<br/>";        }        echo '------------------(while)-----------------'."<br/>";        $it->rewind();//如果要使用current必须使用rewind        while ($it -> valid()) {            echo $it->key().":".$it->current()."<br/>";            $it -> next();        }        echo '------------------跳过某些元素进行打印(while)-----------------'."<br/>";        $it->rewind();        if($it->valid()){            $it -> seek(1);//当前指针指向position=1            while ($it -> valid()) {                echo $it->key().":".$it->current()."<br/>";                $it -> next();            }        }        echo '------------------用迭代器的key进行排序(ksort)-----------------'."<br/>";        $it->ksort();        foreach ($it as $key => $value) {            echo $key.":".$value."<br/>";        }        echo '------------------用迭代器的value进行排序(asort)-----------------'."<br/>";        $it->asort();        foreach ($it as $key => $value) {            echo $key.":".$value."<br/>";        }    }   }

运行结果

array(4) {  ["apple"] => string(11) "apple value"  ["orange"] => string(12) "orange value"  ["grape"] => string(11) "brape value"  ["plum"] => string(10) "plum value"}------------------普通数组遍历-----------------apple:apple valueorange:orange valuegrape:brape valueplum:plum value------------------使用ArrayIterator迭代器遍历数组(foreach)-----------------apple:apple valueorange:orange valuegrape:brape valueplum:plum value------------------(while)-----------------apple:apple valueorange:orange valuegrape:brape valueplum:plum value------------------跳过某些元素进行打印(while)-----------------orange:orange valuegrape:brape valueplum:plum value------------------用迭代器的key进行排序(ksort)-----------------apple:apple valuegrape:brape valueorange:orange valueplum:plum value------------------用迭代器的value进行排序(asort)-----------------apple:apple valuegrape:brape valueorange:orange valueplum:plum value
原创粉丝点击