| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552 | <?php// +----------------------------------------------------------------------// | ThinkPHP [ WE CAN DO IT JUST THINK ]// +----------------------------------------------------------------------// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.// +----------------------------------------------------------------------// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )// +----------------------------------------------------------------------// | Author: zhangyajun <448901948@qq.com>// +----------------------------------------------------------------------namespace think;use ArrayAccess;use ArrayIterator;use Countable;use IteratorAggregate;use JsonSerializable;class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable{    /**     * 数据集数据     * @var array     */    protected $items = [];    public function __construct($items = [])    {        $this->items = $this->convertToArray($items);    }    public static function make($items = [])    {        return new static($items);    }    /**     * 是否为空     * @access public     * @return bool     */    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;    }    /**     * 合并数组     *     * @access public     * @param  mixed $items     * @return static     */    public function merge($items)    {        return new static(array_merge($this->items, $this->convertToArray($items)));    }    /**     * 交换数组中的键和值     *     * @access public     * @return static     */    public function flip()    {        return new static(array_flip($this->items));    }    /**     * 按指定键整理数据     *     * @access public     * @param  mixed    $items      数据     * @param  string   $indexKey   键名     * @return array     */    public function dictionary($items = null, &$indexKey = null)    {        if ($items instanceof self || $items instanceof Paginator) {            $items = $items->all();        }        $items = is_null($items) ? $this->items : $items;        if ($items && empty($indexKey)) {            $indexKey = is_array($items[0]) ? 'id' : $items[0]->getPk();        }        if (isset($indexKey) && is_string($indexKey)) {            return array_column($items, null, $indexKey);        }        return $items;    }    /**     * 比较数组,返回差集     *     * @access public     * @param  mixed    $items      数据     * @param  string   $indexKey   指定比较的键名     * @return static     */    public function diff($items, $indexKey = null)    {        if ($this->isEmpty() || is_scalar($this->items[0])) {            return new static(array_diff($this->items, $this->convertToArray($items)));        }        $diff       = [];        $dictionary = $this->dictionary($items, $indexKey);        if (is_string($indexKey)) {            foreach ($this->items as $item) {                if (!isset($dictionary[$item[$indexKey]])) {                    $diff[] = $item;                }            }        }        return new static($diff);    }    /**     * 比较数组,返回交集     *     * @access public     * @param  mixed    $items      数据     * @param  string   $indexKey   指定比较的键名     * @return static     */    public function intersect($items, $indexKey = null)    {        if ($this->isEmpty() || is_scalar($this->items[0])) {            return new static(array_diff($this->items, $this->convertToArray($items)));        }        $intersect  = [];        $dictionary = $this->dictionary($items, $indexKey);        if (is_string($indexKey)) {            foreach ($this->items as $item) {                if (isset($dictionary[$item[$indexKey]])) {                    $intersect[] = $item;                }            }        }        return new static($intersect);    }    /**     * 返回数组中所有的键名     *     * @access public     * @return array     */    public function keys()    {        $current = current($this->items);        if (is_scalar($current)) {            $array = $this->items;        } elseif (is_array($current)) {            $array = $current;        } else {            $array = $current->toArray();        }        return array_keys($array);    }    /**     * 删除数组的最后一个元素(出栈)     *     * @access public     * @return mixed     */    public function pop()    {        return array_pop($this->items);    }    /**     * 通过使用用户自定义函数,以字符串返回数组     *     * @access public     * @param  callable $callback     * @param  mixed    $initial     * @return mixed     */    public function reduce(callable $callback, $initial = null)    {        return array_reduce($this->items, $callback, $initial);    }    /**     * 以相反的顺序返回数组。     *     * @access public     * @return static     */    public function reverse()    {        return new static(array_reverse($this->items));    }    /**     * 删除数组中首个元素,并返回被删除元素的值     *     * @access public     * @return mixed     */    public function shift()    {        return array_shift($this->items);    }    /**     * 在数组结尾插入一个元素     * @access public     * @param  mixed  $value     * @param  mixed  $key     * @return void     */    public function push($value, $key = null)    {        if (is_null($key)) {            $this->items[] = $value;        } else {            $this->items[$key] = $value;        }    }    /**     * 把一个数组分割为新的数组块.     *     * @access public     * @param  int  $size     * @param  bool $preserveKeys     * @return static     */    public function chunk($size, $preserveKeys = false)    {        $chunks = [];        foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) {            $chunks[] = new static($chunk);        }        return new static($chunks);    }    /**     * 在数组开头插入一个元素     * @access public     * @param mixed  $value     * @param mixed  $key     * @return void     */    public function unshift($value, $key = null)    {        if (is_null($key)) {            array_unshift($this->items, $value);        } else {            $this->items = [$key => $value] + $this->items;        }    }    /**     * 给每个元素执行个回调     *     * @access public     * @param  callable $callback     * @return $this     */    public function each(callable $callback)    {        foreach ($this->items as $key => $item) {            $result = $callback($item, $key);            if (false === $result) {                break;            } elseif (!is_object($item)) {                $this->items[$key] = $result;            }        }        return $this;    }    /**     * 用回调函数处理数组中的元素     * @access public     * @param  callable|null $callback     * @return static     */    public function map(callable $callback)    {        return new static(array_map($callback, $this->items));    }    /**     * 用回调函数过滤数组中的元素     * @access public     * @param  callable|null $callback     * @return static     */    public function filter(callable $callback = null)    {        if ($callback) {            return new static(array_filter($this->items, $callback));        }        return new static(array_filter($this->items));    }    /**     * 根据字段条件过滤数组中的元素     * @access public     * @param  string   $field 字段名     * @param  mixed    $operator 操作符     * @param  mixed    $value 数据     * @return static     */    public function where($field, $operator, $value = null)    {        if (is_null($value)) {            $value    = $operator;            $operator = '=';        }        return $this->filter(function ($data) use ($field, $operator, $value) {            if (strpos($field, '.')) {                list($field, $relation) = explode('.', $field);                $result = isset($data[$field][$relation]) ? $data[$field][$relation] : null;            } else {                $result = isset($data[$field]) ? $data[$field] : null;            }            switch (strtolower($operator)) {                case '===':                    return $result === $value;                case '!==':                    return $result !== $value;                case '!=':                case '<>':                    return $result != $value;                case '>':                    return $result > $value;                case '>=':                    return $result >= $value;                case '<':                    return $result < $value;                case '<=':                    return $result <= $value;                case 'like':                    return is_string($result) && false !== strpos($result, $value);                case 'not like':                    return is_string($result) && false === strpos($result, $value);                case 'in':                    return is_scalar($result) && in_array($result, $value, true);                case 'not in':                    return is_scalar($result) && !in_array($result, $value, true);                case 'between':                    list($min, $max) = is_string($value) ? explode(',', $value) : $value;                    return is_scalar($result) && $result >= $min && $result <= $max;                case 'not between':                    list($min, $max) = is_string($value) ? explode(',', $value) : $value;                    return is_scalar($result) && $result > $max || $result < $min;                case '==':                case '=':                default:                    return $result == $value;            }        });    }    /**     * 返回数据中指定的一列     * @access public     * @param mixed $columnKey 键名     * @param mixed $indexKey  作为索引值的列     * @return array     */    public function column($columnKey, $indexKey = null)    {        return array_column($this->items, $columnKey, $indexKey);    }    /**     * 对数组排序     *     * @access public     * @param  callable|null $callback     * @return static     */    public function sort(callable $callback = null)    {        $items = $this->items;        $callback = $callback ?: function ($a, $b) {            return $a == $b ? 0 : (($a < $b) ? -1 : 1);        };        uasort($items, $callback);        return new static($items);    }    /**     * 指定字段排序     * @access public     * @param  string       $field 排序字段     * @param  string       $order 排序     * @param  bool         $intSort 是否为数字排序     * @return $this     */    public function order($field, $order = null, $intSort = true)    {        return $this->sort(function ($a, $b) use ($field, $order, $intSort) {            $fieldA = isset($a[$field]) ? $a[$field] : null;            $fieldB = isset($b[$field]) ? $b[$field] : null;            if ($intSort) {                return 'desc' == strtolower($order) ? $fieldB >= $fieldA : $fieldA >= $fieldB;            } else {                return 'desc' == strtolower($order) ? strcmp($fieldB, $fieldA) : strcmp($fieldA, $fieldB);            }        });    }    /**     * 将数组打乱     *     * @access public     * @return static     */    public function shuffle()    {        $items = $this->items;        shuffle($items);        return new static($items);    }    /**     * 截取数组     *     * @access public     * @param  int  $offset     * @param  int  $length     * @param  bool $preserveKeys     * @return static     */    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字符串     * @access public     * @param  integer $options json参数     * @return string     */    public function toJson($options = JSON_UNESCAPED_UNICODE)    {        return json_encode($this->toArray(), $options);    }    public function __toString()    {        return $this->toJson();    }    /**     * 转换成数组     *     * @access public     * @param  mixed $items     * @return array     */    protected function convertToArray($items)    {        if ($items instanceof self) {            return $items->all();        }        return (array) $items;    }}
 |