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()方法。

  • 相关阅读:
    CentOS 6的服务器后执行yum后发现出现Error: Cannot find a valid baseurl for repo: base解决办法
    C# 8字节byte数组转int
    Unity Packages 介绍
    开发笔记:服务端返回三/多级菜单数据的几种不同实现
    Grafana Azure Data Explorer Plug-In 中国区 ADX 支持
    Redash 连接中国区 Azure Data Explorer
    爆竹声中贺新年-- KEDA(Kubernetes Event-driven Autoscaling) 带你烟火秀
    生产随机码包含数字+字母
    关于串口通信发送组合键方法
    python 正则匹配一串字符串的负数和正数,合并两个列表为字典
  • 原文地址:https://www.cnblogs.com/freephp/p/4630066.html
Copyright © 2011-2022 走看看