企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 数组处理 - 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]; ~~~