zoukankan      html  css  js  c++  java
  • SPL學習之SplDoublyLinkedList

    Standard PHP Library(SPL)是官方提供的标准库,从php5.0.0开始已经默认实现在php中,我们可以类比它为ruby中的gem安装的包。spl里面实现了许多迭代器和数据结构对象接口,非常实用和高效。下面是我的学习记录:

    从php5.0.0之后才默认可用,而在php5.3.0开始这个扩展将一直开启,且不在php.ini内配置。

    根据php.net/spl 相关文档描述,spl分为以下7种大类:

    1.Datastructures数据结构对象。

    2.Iterators迭代器。

    3.interfaces接口。

    4.Exceptions异常。

    5.SPL Functions标准函数。

    6.File Handling文件资源句柄。

    7.Miscellaneous Classes and Interfaces多元类和接口。

    下面我依次总结:

    1.Datastructures

    数据结构一直都是编程的主力。以前我们所说的堆、栈、队列,链表,树等。程序=数据结构+算法,已经成了大部分的人共识,在处理一些特定问题,选择适当的数据结构能够事半功倍。

    1.The SplDoublyLinkedList class (双向链表)
    双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。(by wiki description)

    funlist can see:

    http://php.net/manual/zh/class.spldoublylinkedlist.php


    // init an object of double Link list
    $dlist = new SplDoublyLinkedList();

    // insert item to the end of the list
    $dlist->push("Linker");
    $dlist->push("Joker");
    $dlist->push("forker");
    $dlist->push("worker");

    // use unshift can insert an object at top of the list
    $dlist->unshift('FreePHP');


    // pop an object from the bottom of the list
    $dlist->pop();

    // delete an object from the top of the list
    $dlist->shift();

    關於遍歷的方式需要用到

    public void SplDoublyLinkedList::setIteratorMode ( int $mode ) 方法

    實現迭代器功能的選項有兩種參數,如下:

    • SplDoublyLinkedList::IT_MODE_LIFO (Stack style)
    • SplDoublyLinkedList::IT_MODE_FIFO (Queue style)

    eg:

    $dlist->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);  // use Stack style
    for($dlist->rewind();$dlist->valid();$dlist->next()){
        echo $dlist->current()."<br/>";;
        }

    spl中有很多實現迭代器模式的經典例子,此爲其一。在數據庫操作中和數據迭代裏面非常常用。

    同样双向链表可以对数据进行序列化和反序列化。

    序列化:

    $ser = $dlist->serialize();
    var_dump($ser);

    // out like this : string(45) "i:2;:s:6:"Linker";:s:5:"Joker";:s:6:"forker";"

    反序列为unserilalize()方法。

  • 相关阅读:
    Working with WordprocessingML documents (Open XML SDK)
    How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
    Azure:Manage anonymous read access to containers and blobs
    Convert HTML to PDF with New Plugin
    location.replace() keeps the history under control
    On the nightmare that is JSON Dates. Plus, JSON.NET and ASP.NET Web API
    HTTP Modules versus ASP.NET MVC Action Filters
    解读ASP.NET 5 & MVC6系列(6):Middleware详解
    Content Negotiation in ASP.NET Web API
    Action Results in Web API 2
  • 原文地址:https://www.cnblogs.com/freephp/p/4630066.html
Copyright © 2011-2022 走看看