本文目录 :

  1. Collection源码
  2. 讲解与例子

PHP 语言最重要的特性之一便是数组了(特别是关联数组)。

PHP 为此也提供不少的函数和类接口方便于数组操作,但没有一个集大成的类专门用来操作数组。

如果数组操作不多的话,个别函数用起来会比较灵活,开销也小。

但是,如果经常操作数组,尤其是对数组进行各种操作如排序、入栈、出队列、翻转、迭代等,系统函数用起来可能就没有那么优雅了。

下面已实现的一个 Collection 类(数据集对象),来自 ThinkPHP5.0 的基础类 Collection,就是一个集大成的类。

1、 Collection源码

源码确实不错,也不是特别长,就全贴上了,方便阅读。跳到下面的 例子 结合看会比较好理解。

namespace think;

use ArrayAccess;
use ArrayIterator;
use Countable;
use IteratorAggregate;
use JsonSerializable;

class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
{
    protected $items = [];

    public function __construct($items = [])
    {
        $this->items = $this->convertToArray($items);
    }
    public static function make($items = [])
    {
        return new static($items);
    }
    public function isEmpty()
    {
        return empty($this->items);
    }
    public function toArray()
    {
        return array_map(function ($value) {
            return ($value instanceof Model || $value instanceof self) ? $value->toArray() : $value;
        }, $this->items);
    }
    public function all()
    {
        return $this->items;
    }
    public function merge($items)
    {
        return new static(array_merge($this->items, $this->convertToArray($items)));
    }
    /**
     * 比较数组,返回差集
     */
    public function diff($items)
    {
        return new static(array_diff($this->items, $this->convertToArray($items)));
    }
    /**
     * 交换数组中的键和值
     */
    public function flip()
    {
        return new static(array_flip($this->items));
    }
    /**
     * 比较数组,返回交集
     */
    public function intersect($items)
    {
        return new static(array_intersect($this->items, $this->convertToArray($items)));
    }
    public function keys()
    {
        return new static(array_keys($this->items));
    }
    /**
     * 删除数组的最后一个元素(出栈)
     */
    public function pop()
    {
        return array_pop($this->items);
    }
    /**
     * 通过使用用户自定义函数,以字符串返回数组
     *
     * @param  callable $callback
     * @param  mixed    $initial
     * @return mixed
     */
    public function reduce(callable $callback, $initial = null)
    {
        return array_reduce($this->items, $callback, $initial);
    }
    /**
     * 以相反的顺序返回数组。
     */
    public function reverse()
    {
        return new static(array_reverse($this->items));
    }
    /**
     * 删除数组中首个元素,并返回被删除元素的值
     */
    public function shift()
    {
        return array_shift($this->items);
    }
    /**
     * 把一个数组分割为新的数组块.
     */
    public function chunk($size, $preserveKeys = false)
    {
        $chunks = [];
        foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) {
            $chunks[] = new static($chunk);
        }
        return new static($chunks);
    }
    /**
     * 在数组开头插入一个元素
     */
    public function unshift($value, $key = null)
    {
        if (is_null($key)) {
            array_unshift($this->items, $value);
        } else {
            $this->items = [$key => $value] + $this->items;
        }
    }
    /**
     * 给每个元素执行个回调
     */
    public function each(callable $callback)
    {
        foreach ($this->items as $key => $item) {
            if ($callback($item, $key) === false) {
                break;
            }
        }
        return $this;
    }
    /**
     * 用回调函数过滤数组中的元素
     */
    public function filter(callable $callback = null)
    {
        if ($callback) {
            return new static(array_filter($this->items, $callback));
        }
        return new static(array_filter($this->items));
    }
    /**
     * 返回数组中指定的一列
     */
    public function column($column_key, $index_key = null)
    {
        if (function_exists('array_column')) {
            return array_column($this->items, $column_key, $index_key);
        }

        $result = [];
        foreach ($this->items as $row) {
            $key    = $value    = null;
            $keySet = $valueSet = false;
            if (null !== $index_key && array_key_exists($index_key, $row)) {
                $keySet = true;
                $key    = (string) $row[$index_key];
            }
            if (null === $column_key) {
                $valueSet = true;
                $value    = $row;
            } elseif (is_array($row) && array_key_exists($column_key, $row)) {
                $valueSet = true;
                $value    = $row[$column_key];
            }
            if ($valueSet) {
                if ($keySet) {
                    $result[$key] = $value;
                } else {
                    $result[] = $value;
                }
            }
        }
        return $result;
    }
    /**
     * 对数组排序
     */
    public function sort(callable $callback = null)
    {
        $items = $this->items;
        $callback ? uasort($items, $callback) : uasort($items, function ($a, $b) {
            if ($a == $b) {
                return 0;
            }
            return ($a < $b) ? -1 : 1;
        });
        return new static($items);
    }
    /**
     * 将数组打乱
     */
    public function shuffle()
    {
        $items = $this->items;
        shuffle($items);
        return new static($items);
    }
    /**
     * 截取数组
     */
    public function slice($offset, $length = null, $preserveKeys = false)
    {
        return new static(array_slice($this->items, $offset, $length, $preserveKeys));
    }
    // ArrayAccess
    public function offsetExists($offset)
    {
        return array_key_exists($offset, $this->items);
    }
    public function offsetGet($offset)
    {
        return $this->items[$offset];
    }
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->items[] = $value;
        } else {
            $this->items[$offset] = $value;
        }
    }
    public function offsetUnset($offset)
    {
        unset($this->items[$offset]);
    }
    //Countable
    public function count()
    {
        return count($this->items);
    }
    //IteratorAggregate
    public function getIterator()
    {
        return new ArrayIterator($this->items);
    }
    //JsonSerializable
    public function jsonSerialize()
    {
        return $this->toArray();
    }
    /**
     * 转换当前数据集为JSON字符串
     */
    public function toJson($options = JSON_UNESCAPED_UNICODE)
    {
        return json_encode($this->toArray(), $options);
    }
    public function __toString()
    {
        return $this->toJson();
    }
    /**
     * 转换成数组
     */
    protected function convertToArray($items)
    {
        if ($items instanceof self) {
            return $items->all();
        }
        return (array) $items;
    }
}

2、 讲解与例子

给出了例子有前后的关系,所以要结合所有例子来看。

Collection 的原理其实都是对 PHP 内置的函数和 SPL 的应用,如果要更加深入,看官方文档也是一个不错的选择。

ArrayAccess的使用

Collection 既然是个类,那要怎么才能像数组那样便利的操作呢?如 $a['key']

答案是:继承接口类 ArrayAccess,并实现该类的几个接口,如下:

abstract public boolean offsetExists ( mixed $offset ) //判断key即$offset的数组元素是否存在,相当于 isset($a[$offset])
abstract public mixed offsetGet ( mixed $offset ) //数组元素获取,相当于 $value = $a[$offset]
abstract public void offsetSet ( mixed $offset , mixed $value ) //数组元素设置 相当于 $a[$offset] = $value
abstract public void offsetUnset ( mixed $offset ) //删除数组元素,相当于 unset($a[$offset]);

现在回头看看 Collection 的源码是怎么实现的。

如何使用,来个例子:

use think;
$c = new Collection;

$c['a'] = 'hello a';
$c['b'] = 'you are b';
echo $c['a'] . '<br/>';
echo $c['b'] . '<br/>';
foreach ($c as $k => $v) {
    echo "key: $k, val: $v <br/>";
}

结果输出:

hello a
you are b
key: a, val: hello a
key: b, val: you are b

JsonSerializable的使用

如果对一个对象进行 json 编码的话,其实就是对该对象的 public 属性进行 json 化,那如何定制 json 化的内容和输出呢?

答案是:继承 JsonSerializable 接口类,并实现类中的接口:

abstract public mixed jsonSerialize ( void ) //定制json化的字符串输出

现在回头看看 Collection 的源码是怎么实现的。

如何使用,来个例子:

echo json_encode($c) . '<br/>';

结果输出:

{"a":"hello a","b":"you are b"}

Countable的使用

如果对一个对象进行 count() 操作的话,其实就是统计该对象的 public 属性的总数,那如何定制 count() 呢?

答案是:继承 Countable 接口类,并实现类中的接口:

abstract public int count ( void )

现在回头看看 Collection 的源码是怎么实现的。

如何使用,来个例子:

echo 'count: ' . $c->count() . '<br/>';
// 或者
echo 'count: ' . count($c) . '<br/>';

结果输出:

count: 2
count: 2

IteratorAggregate、ArrayIterator的使用

如何实现迭代器的功能?如可进行 foreach 操作,提供迭代相关的函数等。

答案是:继承接口类 IteratorAggregate (聚合式迭代器),并实现类中的接口:

abstract public Traversable getIterator ( void )

如何实现该接口,调用生成一个 ArrayIterator 类,该类可提供迭代器的所有功能。

现在回头看看 Collection 的源码是怎么实现的。

如何使用,来个例子:

$c['c'] = 'not just c';
$iter = $c->getIterator(); //获取迭代器
// 可方便地使用foreach操作
foreach ($iter as $k => $v) {
    echo "key: $k, val: $v <br/>";
}
echo 'count: ' . $iter->count() . '<br/>'; // 当前数组元素个数
$iter->rewind(); // 数组位置复位
echo 'current: ' . $iter->current() . '<br/>'; // 当前位置数组元素的值

结果输出:

key: a, val: hello a
key: b, val: you are b
key: c, val: not just c
count: 3
current: hello a

内置函数的使用

功能操作的一般使用内置函数,PHP 提供的内置函数功能已经很强大了,只需要简单地封装成一个类方法即可,函数其实使用不难,忘记怎么使用了去官网溜溜吧。

有些是为了兼容 PHP 低版本,所以还要另外实现一遍,如:

/**
 * 返回数组中指定的一列
 */
public function column($column_key, $index_key = null)

内置的 array_column() 需要 PHP5.5及以上版本才支持,而Collection类的应用目标是5.4及以上能使用,所以勉为其难地再实现了一遍。

-end-

版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
发表日期:2017年5月20日

PHP实现Collection数据集类及其原理的更多相关文章

  1. 【转载】Lua中实现类的原理

    原文地址 http://wuzhiwei.net/lua_make_class/ 不错,将metatable讲的很透彻,我终于懂了. --------------------------------- ...

  2. Java并发包——线程安全的Collection相关类

    Java并发包——线程安全的Collection相关类 摘要:本文主要学习了Java并发包下线程安全的Collection相关的类. 部分内容来自以下博客: https://www.cnblogs.c ...

  3. Java多线程——ThreadLocal类的原理和使用

    Java多线程——ThreadLocal类的原理和使用 摘要:本文主要学习了ThreadLocal类的原理和使用. 概述 是什么 ThreadLocal可以用来维护一个变量,提供了一个ThreadLo ...

  4. 集合(Collection)类

    集合(Collection)类是专门用于数据存储和检索的类.这些类提供了对栈(stack).队列(queue).列表(list)和哈希表(hash table)的支持.大多数集合类实现了相同的接口. ...

  5. java类什么时候加载?,加载类的原理机制是怎么样的?

    java类什么时候加载?,加载原理机制是怎么样的?   答: 很多人都不是很清楚java的class类什么时候加载在运行内存中,其实类加载的时间是发生在一下几种情况: 1.实例化对象时,就像sprin ...

  6. 《前端之路》- TypeScript (三) ES5 中实现继承、类以及原理

    目录 一.先讲讲 ES5 中构造函数(类)静态方法和多态 1-1 JS 中原型以及原型链 例子一 1-2 JS 中原型以及原型链中,我们常见的 constructor.prototype.**prot ...

  7. 第29天学习打卡(迭代器、泛型 、Collection工具类、set集合的特点及应用、Map集合的特点及应用)

    迭代器 对过程的重复,称为迭代. 迭代器是遍历Collection集合的通用方式,可以在对集合遍历的同时进行添加.删除等操作. 迭代器的常用方法 next():返回迭代的下一个元素对象 hasNext ...

  8. Collection工具类

    Collection工具类: 集合工具类,定义除了存取以外的集合常用方法 方法: public static void reverse(List<?> list)   //反转集合中元素的 ...

  9. 一图详解java-class类文件原理

    摘要:徒手制作一张超大的类文件解析图,方便通过浏览这个图能马上回忆起class文件的结构以及内部的指令. 本文分享自华为云社区<[读书会第十二期]这可能是全网"最大".&qu ...

随机推荐

  1. tmux配置

    bind k selectp -U bind j selectp -D bind h selectp -L bind l selectp -R bind -r ^k resizep -U 5 bind ...

  2. 【one day one linux】find 用法详解小记

    find命令的功能很强大,查找文件的选项很多,所以这是一个很实用并且很常用的linux命令.但是他有个缺点就是搜索的时候比较慢的.而与之相对的有一个locate命令. find的命令格式 find   ...

  3. 针对Mac的DuckHunter攻击演示

    0x00 HID 攻击 HID是Human Interface Device的缩写,也就是人机交互设备,说通俗一点,HID设备一般指的是键盘.鼠标等等这一类用于为计算机提供数据输入的设备. DuckH ...

  4. 使用 rsync 同步

    原文地址 http://www.howtocn.org/rsync:use_rsync 选项 说明 -a, ––archive 归档模式,表示以递归方式传输文件,并保持所有文件属性,等价于 -rlpt ...

  5. 完美实现在同一个页面中使用不同样式的artDialog样式

    偶然发现artDialog.js这个插件,就被其优雅的设计及漂亮的效果深深吸引,在做例子时碰到了一些想当然它应该提供但却没有提供的功能,不过这都不影响我对它的喜爱,下面说一下遇到的问题吧! artDi ...

  6. 安装hexo报错(npm WARN deprecated swig@1.4.2: This package is no longer maintained),已解决

    问题:在使用npm安装hexo时报错 $ npm install -g hexo npm WARN deprecated swig@1.4.2: This package is no longer m ...

  7. Linux下Hadoop2.7.1集群环境的搭建(超详细版)

                                本文旨在提供最基本的,可以用于在生产环境进行Hadoop.HDFS分布式环境的搭建,对自己是个总结和整理,也能方便新人学习使用. 一.基础环境 ...

  8. redis 主从配置实例、注意事项、及备份方式

    这两天在配置线上使用的redis服务.总得看起来,redis服务的配置文件还是非常简洁.清楚,配置起来非常顺畅,赞一下作者. 下面是我使用的配置,使用主从模式,在master上关掉所有持久化,在sla ...

  9. path sum i

    Problem Statement:  Path sum i Given a binary tree and a sum, determine if the tree has a root-to-le ...

  10. 【初识Python】

    一.Python的简介 1.什么是python? Python(发音:[ 'paiθ(ə)n; (US) 'paiθɔn ]),是一种面向对象的解释性的计算机程序设计语言,也是一种功能强大而完善的通用 ...