溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

PHP實(shí)現(xiàn)Collection數(shù)據(jù)集類及其原理

發(fā)布時間:2020-07-30 12:33:07 來源:網(wǎng)絡(luò) 閱讀:7886 作者:zsdnr 欄目:web開發(fā)

PHP 語言最重要的特性之一便是數(shù)組了(特別是關(guān)聯(lián)數(shù)組)。
PHP 為此也提供不少的函數(shù)和類接口方便于數(shù)組操作,但沒有一個集大成的類專門用來操作數(shù)組。

如果數(shù)組操作不多的話,個別函數(shù)用起來會比較靈活,開銷也小。
但是,如果經(jīng)常操作數(shù)組,尤其是對數(shù)組進(jìn)行各種操作如排序、入棧、出隊列、翻轉(zhuǎn)、迭代等,系統(tǒng)函數(shù)用起來可能就沒有那么優(yōu)雅了。

下面已實(shí)現(xiàn)的一個 Collection 類(數(shù)據(jù)集對象),來自 ThinkPHP5.0 的基礎(chǔ)類 Collection,就是一個集大成的類。


1、 Collection源碼

源碼確實(shí)不錯,也不是特別長,就全貼上了,方便閱讀。跳到下面的 例子 結(jié)合看會比較好理解。

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)));
    }    /**     * 比較數(shù)組,返回差集     */
    public function diff($items)
    {        return new static(array_diff($this->items, $this->convertToArray($items)));
    }    /**     * 交換數(shù)組中的鍵和值     */
    public function flip()
    {        return new static(array_flip($this->items));
    }    /**     * 比較數(shù)組,返回交集     */
    public function intersect($items)
    {        return new static(array_intersect($this->items, $this->convertToArray($items)));
    }    public function keys()
    {        return new static(array_keys($this->items));
    }    /**     * 刪除數(shù)組的最后一個元素(出棧)     */
    public function pop()
    {        return array_pop($this->items);
    }    /**     * 通過使用用戶自定義函數(shù),以字符串返回數(shù)組     *     * @param  callable $callback     * @param  mixed    $initial     * @return mixed     */
    public function reduce(callable $callback, $initial = null)
    {        return array_reduce($this->items, $callback, $initial);
    }    /**     * 以相反的順序返回數(shù)組。     */
    public function reverse()
    {        return new static(array_reverse($this->items));
    }    /**     * 刪除數(shù)組中首個元素,并返回被刪除元素的值     */
    public function shift()
    {        return array_shift($this->items);
    }    /**     * 把一個數(shù)組分割為新的數(shù)組塊.     */
    public function chunk($size, $preserveKeys = false)
    {        $chunks = [];
        foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) {            $chunks[] = new static($chunk);
        }        return new static($chunks);
    }    /**     * 在數(shù)組開頭插入一個元素     */
    public function unshift($value, $key = null)
    {        if (is_null($key)) {            array_unshift($this->items, $value);
        } else {            $this->items = [$key => $value] + $this->items;
        }
    }    /**     * 給每個元素執(zhí)行個回調(diào)     */
    public function each(callable $callback)
    {        foreach ($this->items as $key => $item) {            if ($callback($item, $key) === false) {                break;
            }
        }        return $this;
    }    /**     * 用回調(diào)函數(shù)過濾數(shù)組中的元素     */
    public function filter(callable $callback = null)
    {        if ($callback) {            return new static(array_filter($this->items, $callback));
        }        return new static(array_filter($this->items));
    }    /**     * 返回數(shù)組中指定的一列     */
    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;
    }    /**     * 對數(shù)組排序     */
    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);
    }    /**     * 將數(shù)組打亂     */
    public function shuffle()
    {        $items = $this->items;
        shuffle($items);
        return new static($items);
    }    /**     * 截取數(shù)組     */
    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();
    }    /**     * 轉(zhuǎn)換當(dāng)前數(shù)據(jù)集為JSON字符串     */
    public function toJson($options = JSON_UNESCAPED_UNICODE)
    {        return json_encode($this->toArray(), $options);
    }    public function __toString()
    {        return $this->toJson();
    }    /**     * 轉(zhuǎn)換成數(shù)組     */
    protected function convertToArray($items)
    {        if ($items instanceof self) {            return $items->all();
        }        return (array) $items;
    }
}


2、 講解與例子

給出了例子有前后的關(guān)系,所以要結(jié)合所有例子來看。
Collection 的原理其實(shí)都是對 PHP 內(nèi)置的函數(shù)和 SPL 的應(yīng)用,如果要更加深入,看官方文檔也是一個不錯的選擇。


ArrayAccess的使用

Collection 既然是個類,那要怎么才能像數(shù)組那樣便利的操作呢?如 $a['key'] 。
答案是:繼承接口類 ArrayAccess,并實(shí)現(xiàn)該類的幾個接口,如下:

abstract public boolean offsetExists ( mixed $offset ) //判斷key即$offset的數(shù)組元素是否存在,相當(dāng)于 isset($a[$offset])abstract public mixed offsetGet ( mixed $offset ) //數(shù)組元素獲取,相當(dāng)于 $value = $a[$offset]abstract public void offsetSet ( mixed $offset , mixed $value ) //數(shù)組元素設(shè)置 相當(dāng)于 $a[$offset] = $valueabstract public void offsetUnset ( mixed $offset ) //刪除數(shù)組元素,相當(dāng)于 unset($a[$offset]);

現(xiàn)在回頭看看 Collection 的源碼是怎么實(shí)現(xiàn)的。
如何使用,來個例子:

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/>";}

結(jié)果輸出:

hello a
you are bkey: a, val: hello akey: b, val: you are b


JsonSerializable的使用

如果對一個對象進(jìn)行 json 編碼的話,其實(shí)就是對該對象的 public 屬性進(jìn)行 json 化,那如何定制 json 化的內(nèi)容和輸出呢?
答案是:繼承 JsonSerializable 接口類,并實(shí)現(xiàn)類中的接口:

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

現(xiàn)在回頭看看 Collection 的源碼是怎么實(shí)現(xiàn)的。
如何使用,來個例子:

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

結(jié)果輸出:

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


Countable的使用

如果對一個對象進(jìn)行 count() 操作的話,其實(shí)就是統(tǒng)計該對象的 public 屬性的總數(shù),那如何定制 count() 呢?
答案是:繼承 Countable 接口類,并實(shí)現(xiàn)類中的接口:

abstract public int count ( void )

現(xiàn)在回頭看看 Collection 的源碼是怎么實(shí)現(xiàn)的。
如何使用,來個例子:

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

結(jié)果輸出:

count: 2count: 2


IteratorAggregate、ArrayIterator的使用

如何實(shí)現(xiàn)迭代器的功能?如可進(jìn)行 foreach 操作,提供迭代相關(guān)的函數(shù)等。
答案是:繼承接口類 IteratorAggregate (聚合式迭代器),并實(shí)現(xiàn)類中的接口:

abstract public Traversable getIterator ( void )

如何實(shí)現(xiàn)該接口,調(diào)用生成一個 ArrayIterator 類,該類可提供迭代器的所有功能。
現(xiàn)在回頭看看 Collection 的源碼是怎么實(shí)現(xiàn)的。
如何使用,來個例子:

$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/>'; // 當(dāng)前數(shù)組元素個數(shù)$iter->rewind(); // 數(shù)組位置復(fù)位echo 'current: ' . $iter->current() . '<br/>'; // 當(dāng)前位置數(shù)組元素的值

結(jié)果輸出:

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


內(nèi)置函數(shù)的使用

功能操作的一般使用內(nèi)置函數(shù),PHP 提供的內(nèi)置函數(shù)功能已經(jīng)很強(qiáng)大了,只需要簡單地封裝成一個類方法即可,函數(shù)其實(shí)使用不難,忘記怎么使用了去官網(wǎng)溜溜吧。

有些是為了兼容 PHP 低版本,所以還要另外實(shí)現(xiàn)一遍,如:

/** * 返回數(shù)組中指定的一列 */public function column($column_key, $index_key = null)

內(nèi)置的 array_column() 需要 PHP5.5及以上版本才支持,而Collection類的應(yīng)用目標(biāo)是5.4及以上能使用,所以勉為其難地再實(shí)現(xiàn)了一遍。


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI