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

十多年的左貢網(wǎng)站建設經(jīng)驗,針對設計、前端、開發(fā)、售后、文案、推廣等六對一服務,響應快,48小時及時工作處理。成都全網(wǎng)營銷推廣的優(yōu)勢是能夠根據(jù)用戶設備顯示端的尺寸不同,自動調整左貢建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設計,從而大程度地提升瀏覽體驗。成都創(chuàng)新互聯(lián)公司從事“左貢網(wǎng)站設計”,“左貢網(wǎng)站推廣”以來,每個客戶項目都認真落實執(zhí)行。
如果數(shù)組操作不多的話,個別函數(shù)用起來會比較靈活,開銷也小。
但是,如果經(jīng)常操作數(shù)組,尤其是對數(shù)組進行各種操作如排序、入棧、出隊列、翻轉、迭代等,系統(tǒng)函數(shù)用起來可能就沒有那么優(yōu)雅了。
下面已實現(xiàn)的一個 Collection 類(數(shù)據(jù)集對象),來自 ThinkPHP5.0 的基礎類 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)));
} /** * 比較數(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í)行個回調 */
public function each(callable $callback)
{ foreach ($this->items as $key => $item) { if ($callback($item, $key) === false) { break;
}
} return $this;
} /** * 用回調函數(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();
} /** * 轉換當前數(shù)據(jù)集為JSON字符串 */
public function toJson($options = JSON_UNESCAPED_UNICODE)
{ return json_encode($this->toArray(), $options);
} public function __toString()
{ return $this->toJson();
} /** * 轉換成數(shù)組 */
protected function convertToArray($items)
{ if ($items instanceof self) { return $items->all();
} return (array) $items;
}
}給出了例子有前后的關系,所以要結合所有例子來看。
Collection 的原理其實都是對 PHP 內置的函數(shù)和 SPL 的應用,如果要更加深入,看官方文檔也是一個不錯的選擇。
Collection 既然是個類,那要怎么才能像數(shù)組那樣便利的操作呢?如 $a['key'] 。
答案是:繼承接口類 ArrayAccess,并實現(xiàn)該類的幾個接口,如下:
abstract public boolean offsetExists ( mixed $offset ) //判斷key即$offset的數(shù)組元素是否存在,相當于 isset($a[$offset])abstract public mixed offsetGet ( mixed $offset ) //數(shù)組元素獲取,相當于 $value = $a[$offset]abstract public void offsetSet ( mixed $offset , mixed $value ) //數(shù)組元素設置 相當于 $a[$offset] = $valueabstract public void offsetUnset ( mixed $offset ) //刪除數(shù)組元素,相當于 unset($a[$offset]);
現(xiàn)在回頭看看 Collection 的源碼是怎么實現(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/>";}結果輸出:
hello a you are bkey: a, val: hello akey: b, val: you are b
如果對一個對象進行 json 編碼的話,其實就是對該對象的 public 屬性進行 json 化,那如何定制 json 化的內容和輸出呢?
答案是:繼承 JsonSerializable 接口類,并實現(xiàn)類中的接口:
abstract public mixed jsonSerialize ( void ) //定制json化的字符串輸出
現(xiàn)在回頭看看 Collection 的源碼是怎么實現(xiàn)的。
如何使用,來個例子:
echo json_encode($c) . '<br/>';
結果輸出:
{"a":"hello a","b":"you are b"}如果對一個對象進行 count() 操作的話,其實就是統(tǒng)計該對象的 public 屬性的總數(shù),那如何定制 count() 呢?
答案是:繼承 Countable 接口類,并實現(xiàn)類中的接口:
abstract public int count ( void )
現(xiàn)在回頭看看 Collection 的源碼是怎么實現(xiàn)的。
如何使用,來個例子:
echo 'count: ' . $c->count() . '<br/>';// 或者echo 'count: ' . count($c) . '<br/>';
結果輸出:
count: 2count: 2
如何實現(xiàn)迭代器的功能?如可進行 foreach 操作,提供迭代相關的函數(shù)等。
答案是:繼承接口類 IteratorAggregate (聚合式迭代器),并實現(xiàn)類中的接口:
abstract public Traversable getIterator ( void )
如何實現(xiàn)該接口,調用生成一個 ArrayIterator 類,該類可提供迭代器的所有功能。
現(xiàn)在回頭看看 Collection 的源碼是怎么實現(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/>'; // 當前數(shù)組元素個數(shù)$iter->rewind(); // 數(shù)組位置復位echo 'current: ' . $iter->current() . '<br/>'; // 當前位置數(shù)組元素的值結果輸出:
key: a, val: hello a key: b, val: you are b key: c, val: not just c count: 3current: hello a
功能操作的一般使用內置函數(shù),PHP 提供的內置函數(shù)功能已經(jīng)很強大了,只需要簡單地封裝成一個類方法即可,函數(shù)其實使用不難,忘記怎么使用了去官網(wǎng)溜溜吧。
有些是為了兼容 PHP 低版本,所以還要另外實現(xiàn)一遍,如:
/** * 返回數(shù)組中指定的一列 */public function column($column_key, $index_key = null)
內置的 array_column() 需要 PHP5.5及以上版本才支持,而Collection類的應用目標是5.4及以上能使用,所以勉為其難地再實現(xiàn)了一遍。
分享名稱:PHP實現(xiàn)Collection數(shù)據(jù)集類及其原理
網(wǎng)頁路徑:http://www.chinadenli.net/article20/gjopjo.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供關鍵詞優(yōu)化、小程序開發(fā)、域名注冊、App開發(fā)、網(wǎng)站排名、營銷型網(wǎng)站建設
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)