在 PHP
語言中操做字符串和數組通常使用 str_*
和 array_*
的系列函數,這些函數因爲歷史緣由,命名和參數順序風格不統一,廣爲開發者詬病,PHP
語言標準庫中暫未提供 OO
風格的 Array
和 String
類庫,開發者使用起來不是很便利,在 Swoole
中咱們提供了一 swoole_array
和 swoole_string
對字符串和數組操做進行了面向對象封裝,能夠使用徹底面向對象風格進行 Array
和 String
編程。php
Swoole
項目:可直接使用Swoole
項目,使用 composer require swoole/library
引入絕大部分方法提供了鏈式風格
支持,能夠一路使用 ->
編寫邏輯。底層類庫使用了 declare(strict_types=1)
強類型,使用 phpstorm
工具時,能夠實現徹底自動提示和自動完成。java
$array1 = swoole_array(['hello', 'world']); $array2 = swoole_array(['hello' => 1, 'world' => 2]); $array3 = swoole_array_list('hello', 'world', 'swoole', 'php');
// Bytes 字符串 $string1 = swoole_string('hello world, php java, swoole'); // 寬字符串 $string2 = swoole_mbstring('我是中國人'); // 返回 5 $string2->length();
// 獲取 $value1 = $array1->get(0); $value2 = $array2->get('hello'); // 數組的第一個元素 $first = $array->first(); // 數組的最後一個元素 $last = $array->last();
// 設置 $array1->set(0, 'swoole'); $array2->set('world', 9); // 在末尾追加 $array1->pushBack('java'); // 在頭部插入 $array1->pushFront('go'); // 在中間 offset 2 插入 $array1->insert(2, 'rust');
$array1->append('rust')->append('c++')->append('swift', 'kotlin'); $array2->set('rust', 99)->set('c++', 88)->set('kotlin', 77);
// 按 key 刪除 $array1->delete(0); $array2->delete('worker'); // 按 value 刪除 $array1->remove('hello');
使用contains()
方法能夠判斷數組或字符串中是否包含某個元素。c++
$array1->contains('java'); $string1->contains('php');
使用startsWith()
和endsWith()
方法判斷字符串開頭和結尾是否爲指定的值。git
$str = swoole_string('php and swoole'); $str->startsWith('php'); //true $str->startsWith('java'); //false $str->endsWith('swoole'); //true $str->endsWith('golang'); //false
// 查找數組中是否有某個值,存在則返回其 key $key = $array1->search('java');
String
與Array
能夠結合使用。github
$s = '11, 33, 22, 44,12,32,55,23,19,23'; $data = swoole_string($s) ->split(',') ->each(fn(&$item) => $item = intval($item)) /* < 7.4 : function (&$item){ $item = intval($item);} */ ->sort() ->unique() ->join('-') ->contains('-44-'); var_dump($data);
split
按照,
分割爲數組$fn
函數將元素轉換爲整數-
組合成爲字符串-44-
對 swoole_array
對象元素操做時,底層會自動判斷它的類型,若是爲數組或字符串,底層會遞歸封裝。golang
$array = swoole_array_list(['hello' => 'swoole']); $array->get(0)->get('hello')->contains('swoole');
底層實現其實就是基於str_
和array_
相關函數進行面向對象封裝,沒有過多性能損耗,僅爲一次method
調用開銷。咱們編寫了嚴格的單測覆蓋到每一個API
,保證其可靠性。shell
性能方面,使用String::contains()
執行100
萬次,與直接運行 php strpos
差距不大。編程
swoole_string: 0.059892892837524s, php_string: 0.033510208129883s
若是您對此項目感興趣,能夠參與到咱們的開發工做中,期待您的 Pull Request
。swift