PHP處理二維數組合並 時間複雜度O(n)
一直沒怎麼寫部落格,感覺很多東西都遺忘, 在寫ArrayAccess同時把時間複雜度溫習下 ,這篇部落格給大家說說關於PHP預定義介面中常用到的重量級人物: ArrayAccess。大家也許會問,最基本、最常用的預定義介面有6個呢,為啥非得說這個。從日常的使用情況來看:這個出現的頻率非常高,特別是在框架中,比如Laravel、Slim等都會用到,並且用得非常經典,讓人佩服啊。從技術上說:說實話其他的我用的少啊!只是知道簡單的用法,對他的理解比較淺顯,不敢在這裡誤導大家,哈哈!今天我要寫的內容也不一定都正確,不對之處還請指正。
ArrayAccess
先說 ArrayAccess 吧!ArrayAccess 的作用是使得你的物件可以像陣列一樣可以被訪問。應該說 ArrayAccess 在PHP5中才開始有的,PHP5中加入了很多新的特性,當然也使類的過載也加強了,PHP5 中添加了一系列介面,這些介面和實現的 Class 統稱為 SPL。
ArrayAccess 這個介面定義了4個必須要實現的方法:
1 { 2abstract public offsetExists ($offset)//檢查偏移位置是否存在 3abstract public offsetGet ($offset)//獲取一個偏移位置的值 4abstract public void offsetSet ($offset ,$value) //設定一個偏移位置的值 5abstract public void offsetUnset ($offset)//復位一個偏移位置的值 6 }
所以我們要使用ArrayAccess這個介面,就要實現相應的方法,
class obj implements ArrayAccess { private $container; public function __construct($data) { $this->container = $data; } public function offsetExists($offset) { // TODO: Implement offsetExists() method. $arrKey = array_search($offset, array_column($this->container, 'bookId')); return $arrKey; } public function offsetSet($offset, $value) { $arrKey=$this->offsetExists($offset); if($arrKey!==false){ // TODO: Implement offsetSet() method. $this->offsetUnset($arrKey); $this->container[$arrKey] = array_merge($this->container[$arrKey], $value); } } public function offsetGet($offset) { // TODO: Implement offsetGet() method. return $this->container; } public function offsetUnset($offset) { unset($this->container[$offset]['bookId']); // TODO: Implement offsetUnset() method. } } $bookBaseInfo = [ ['bookId' => 1, 'name' => '程式設計師修煉之道'], ['bookId' => 2, 'name' => '擇天記'], ['bookId' => 3, 'name' => 'PHP核心'], ]; $bookUpdateTime = [ ['bookId' => 3, 'timestamp' => 11], ['bookId' => 2, 'timestamp' => 22], ]; $obj = new obj($bookBaseInfo); foreach ($bookUpdateTime as $key => $value) { $obj[$value['bookId']]=$value; } var_dump($obj['bookId']);die;
這個示例裡面只用一層迴圈 ,所以時間事件複雜度是O(n);