入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

PHP实现Collection数据集类及其原理

创建时间:2017-06-08 投稿人: 浏览次数:139

本文目录 :

  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;
    }
}
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。