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

本文介绍了PHP中Collection数据集类的实现与原理,详细解析了ArrayAccess、JsonSerializable、Countable、IteratorAggregate和内置函数的使用,通过实例展示了如何像操作数组一样便捷地操作Collection对象,提供更优雅的数组操作解决方案。
摘要由CSDN通过智能技术生成
本文目录 :
  1. Collection源码
  2. 讲解与例子
    • ArrayAccess的使用
    • JsonSerializable的使用
    • Countable的使用
    • IteratorAggregate、ArrayIterator的使用
    • 内置函数的使用



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)
    {
        ret
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值