# 數組處理 - Nette \ Utils \ Arrays
Nette \ Utils \ Arrays是一個靜態類,它包含一些方便的數組函數。
所有示例假定定義了以下類別名:
~~~
use Nette\Utils\Arrays;
~~~
get($array, $key, $default=NULL)
返回$ array [$ key] item。 如果不存在,則拋出Nette \ InvalidArgumentException,除非將缺省返回值設置為第三個參數。
~~~
// if $array['foo'] does not exist, throws an exception
$value = Arrays::get($array, 'foo');
// if $array['foo'] does not exist, returns 'bar'
$value = Arrays::get($array, 'foo', 'bar');
~~~
參數$ key也可以是數組。
~~~
$array = ['color' => ['favorite' => 'red'], 5];
$value = Arrays::get($array, ['color', 'favorite']);
// returns 'red'
~~~
getRef(&$array, $key)
獲取給定的$ array [$ key]的引用。 如果索引不存在,則使用NULL創建新索引。
~~~
$valueRef = & Arrays::getRef($array, 'foo');
// returns $array['foo'] reference
~~~
適用于多維數組以及get()。
~~~
$value = & Arrays::get($array, ['color', 'favorite']);
// returns $array['color']['favorite'] reference
~~~
grep($array, $pattern, $flags=NULL)
僅返回與正則表達式$ pattern匹配的數組項。 正則表達式編譯或運行時錯誤拋出Nette \ RegexpException。
~~~
$filteredArray = Arrays::grep($array, '~^\d+$~');
// returns only numerical items
~~~
值PREG_GREP_INVERT可以設置為$ flags,它反轉選擇。
searchKey($array, $key)
返回給定數組鍵的零索引位置。 如果未找到鍵,則返回FALSE。
~~~
$array = ['first' => 10, 'second' => 20];
$position = Arrays::searchKey($array, 'first'); // returns 0
~~~
insertAfter(&$array, $key, $inserted)
在$ key索引后追加數組$key。 如果這樣的$鍵不存在,則在末尾插入數組。
~~~
$array = ['first' => 10, 'second' => 20];
Arrays::insertAfter($array, 'first', ['hello' => 'world']);
// $array = ['first' => 10, 'hello' => 'world', 'second' => 20];
~~~
insertBefore(&$array, $key, $inserted)
將$ inserted數組的內容前置到帶有$ key索引的項目前的$ array中。 如果這樣的$鍵不存在,數組被插入開頭。
~~~
$array = ['first' => 10, 'second' => 20];
Arrays::insertBefore($array, 'first', ['hello' => 'world']);
// $array = ['hello' => 'world', 'first' => 10, 'second' => 20];
~~~
mergeTree($array1, $array2)
遞歸合并兩個數組。 用于組合樹結構。 它表現為應用于數組的+運算符,即。 它將第二個數組的鍵/值添加到第一個數組。 在沖突的情況下,使用第一數組的值。
~~~
$array1 = ['color' => ['favorite' => 'red'], 5];
$array2 = [10, 'color' => ['favorite' => 'green', 'blue']];
$array = Arrays::mergeTree($array1, $array2);
// $array = ['color' => ['favorite' => 'red', 'blue'], 5];
~~~
第二個數組的值總是追加到第一個數組。 雖然值10的消失可能會令人困惑,但很好 - 第一個數組中的5個和10個都有相同的鍵0。
renameKey(&$array, $oldKey, $newKey)
重命名鍵。
~~~
$array = ['first' => 10, 'second' => 20];
Arrays::renameKey($array, 'first', 'renamed');
// $array = ['renamed' => 10, 'second' => 20];
~~~
- Nette簡介
- 快速開始
- 入門
- 主頁
- 顯示文章詳細頁
- 文章評論
- 創建和編輯帖子
- 權限驗證
- 程序員指南
- MVC應用程序和控制器
- URL路由
- Tracy - PHP調試器
- 調試器擴展
- 增強PHP語言
- HTTP請求和響應
- 數據庫
- 數據庫:ActiveRow
- 數據庫和表
- Sessions
- 用戶授權和權限
- 配置
- 依賴注入
- 獲取依賴關系
- DI容器擴展
- 組件
- 字符串處理
- 數組處理
- HTML元素
- 使用URL
- 表單
- 驗證器
- 模板
- AJAX & Snippets
- 發送電子郵件
- 圖像操作
- 緩存
- 本土化
- Nette Tester - 單元測試
- 與Travis CI的持續集成
- 分頁
- 自動加載
- 文件搜索:Finder
- 原子操作