Yii2 yii\helpers\ArrayHelper

yii\helpers\ArrayHelper 是一个数组辅助类,提供额外的数组功能函数

  • toArray($object, $properties = [], $recursive = true) 

Converts an object or an array of objects into an array (把对象、数组、字符串安装条件重新转换成数组)

源代码中的例子:

 1 $properties = 
 2 [
 3  'app\models\Post' => [
 4  'id',
 5  'title',
 6  // the key name in array result => property name
 7  'createTime' => 'created_at',
 8 // the key name in array result => anonymous function
 9  'length' => function ($post) {
10  return strlen($post->content);
11  },
12  ],
13  ]
14 $result = ArrayHelper::toArray($post, $properties) ;
15 //The result of `ArrayHelper::toArray($post, $properties)` could be like the following (结果如下):
16  * ```php
17      * [
18      *     'id' => 123,
19      *     'title' => 'test',
20      *     'createTime' => '2013-01-01 12:00AM',
21      *     'length' => 301,
22      * ]
23      * ```
24 */

 

  •  merge($a, $b)数组合并 ,支持无限个参数数组合并
 1   public static function merge($a, $b)
 2     {
 3         $args = func_get_args();
 4         $res = array_shift($args);
 5         while (!empty($args)) {
 6             $next = array_shift($args);
 7             foreach ($next as $k => $v) {
 8                 if ($v instanceof UnsetArrayValue) {
 9                     unset($res[$k]);
10                 } elseif ($v instanceof ReplaceArrayValue) {
11                     $res[$k] = $v->value;
12                 } elseif (is_int($k)) {
13                     if (isset($res[$k])) {
14                         $res[] = $v;
15                     } else {
16                         $res[$k] = $v;
17                     }
18                 } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
19                     $res[$k] = self::merge($res[$k], $v);
20                 } else {
21                     $res[$k] = $v;
22                 }
23             }
24         }
25 
26         return $res;
27     }

其中if ($v instanceof UnsetArrayValue) { unset($res[$k])};

 UnsetArrayValue   yii\helpers\UnsetArrayValue  类注释可以看出具体作用

/**
 * Object that represents the removal of array value while performing [[ArrayHelper::merge()]].
 *
 * Usage example:
 *
 * ```php
 * $array1 = [
 *     'ids' => [
 *         1,
 *     ],
 *     'validDomains' => [
 *         'example.com',
 *         'www.example.com',
 *     ],
 * ];
 *
 * $array2 = [
 *     'ids' => [
 *         2,
 *     ],
 *     'validDomains' => new \yii\helpers\UnsetArrayValue(),
 * ];
 *
 * $result = \yii\helpers\ArrayHelper::merge($array1, $array2);
 * ```
 *
 * The result will be
 *
 * ```php
 * [
 *     'ids' => [
 *         1,
 *         2,
 *     ],
 * ]
 * ```
 *
 * @author Robert Korulczyk <robert@korulczyk.pl>
 * @since 2.0.10
 */

其中elseif ($v instanceof ReplaceArrayValue) { $res[$k] = $v->value};

 UnsetArrayValue   yii\helpers\ReplaceArrayValue类注释可以看出具体作用

 1 /**
 2  * Object that represents the replacement of array value while performing [[ArrayHelper::merge()]].
 3  *
 4  * Usage example:
 5  *
 6  * ```php
 7  * $array1 = [
 8  *     'ids' => [
 9  *         1,
10  *     ],
11  *     'validDomains' => [
12  *         'example.com',
13  *         'www.example.com',
14  *     ],
15  * ];
16  *
17  * $array2 = [
18  *     'ids' => [
19  *         2,
20  *     ],
21  *     'validDomains' => new \yii\helpers\ReplaceArrayValue([
22  *         'yiiframework.com',
23  *         'www.yiiframework.com',
24  *     ]),
25  * ];
26  *
27  * $result = \yii\helpers\ArrayHelper::merge($array1, $array2);
28  * ```
29  *
30  * The result will be
31  *
32  * ```php
33  * [
34  *     'ids' => [
35  *         1,
36  *         2,
37  *     ],
38  *     'validDomains' => [
39  *         'yiiframework.com',
40  *         'www.yiiframework.com',
41  *     ],
42  * ]
43  * ```
44  *
45  * @author Robert Korulczyk <robert@korulczyk.pl>
46  * @since 2.0.10
47  */

getValue($array, $key, $default = null)  根据数组的键获取数组元素的值或者根据对象的属性名称或者对象的属性值

 1 /**
 2 * ```php
 3      * // working with array 数组
 4      * $username = \yii\helpers\ArrayHelper::getValue($_POST, 'username');
 5      * // working with object 对象
 6      * $username = \yii\helpers\ArrayHelper::getValue($user, 'username');
 7      * // working with anonymous function 匿名函数
 8      * $fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) {
 9      *     return $user->firstName . ' ' . $user->lastName;
10      * });
11      * // using dot format to retrieve(得到) the property of embedded(嵌入、内嵌式) object 
12      * $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
13      * // using an array of keys to retrieve the value
14      * $value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
15      * ```
16 */
  • remove(&$array, $key, $default = null) 删除数组指定键值
  • getColumn($array, $name, $keepKeys = true) 在一个数组中获取指定列的值,由指定列的值组成新的数组返回  参数$keepKeys返回数组是否保持第一层的key
 1 /**
 2      * Returns the values of a specified column in an array.
 3      * The input array should be multidimensional(多维的) or an array of objects.
 4      *
 5      * For example,
 6      *
 7      * ```php
 8      * $array = [
 9      *     ['id' => '123', 'data' => 'abc'],
10      *     ['id' => '345', 'data' => 'def'],
11      * ];
12      * $result = ArrayHelper::getColumn($array, 'id');
13      * // the result is: ['123', '345']
14      *
15      * // using anonymous function
16      * $result = ArrayHelper::getColumn($array, function ($element) {
17      *     return $element['id'];
18      * });
19      * ```
20      *
21      * @param array $array
22      * @param string|\Closure $name
23      * @param boolean $keepKeys whether to maintain(维持、保持) the array keys. If false, the resulting array
24      * will be re-indexed with integers.
25      * @return array the list of column values
26      */

map($array, $from, $to, $group = null) 从一个多维数组或者对象中建立一个键值对的映射组成新的数组返回

 1 /**
 2      * Builds a map (key-value pairs) from a multidimensional(多维的) array or an array of objects.
 3      * The `$from` and `$to` parameters specify the key names or property names to set up(建立) the map(映射、地图).
 4      * Optionally, one can further group the map according to a grouping field `$group`.
 5      *
 6      * For example,
 7      *
 8      * ```php
 9      * $array = [
10      *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
11      *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
12      *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
13      * ];
14      *
15      * $result = ArrayHelper::map($array, 'id', 'name');
16      * // the result is:
17      * // [
18      * //     '123' => 'aaa',
19      * //     '124' => 'bbb',
20      * //     '345' => 'ccc',
21      * // ]
22      *
23      * $result = ArrayHelper::map($array, 'id', 'name', 'class');
24      * // the result is:
25      * // [
26      * //     'x' => [
27      * //         '123' => 'aaa',
28      * //         '124' => 'bbb',
29      * //     ],
30      * //     'y' => [
31      * //         '345' => 'ccc',
32      * //     ],
33      * // ]
34      * ```
35      *
36      * @param array $array
37      * @param string|\Closure $from
38      * @param string|\Closure $to
39      * @param string|\Closure $group
40      * @return array
41      */
  • keyExists($key, $array, $caseSensitive = true) 检查数组是否存在指定的键 $caseSensitive 参数 是否区分大小写 默认ture区分
  • isIn($needle, $haystack, $strict = false) Check whether an array or [[\Traversable]] contains an element. 检查数组或者 可遍历的元素 (\Traversable )是否包含指定元素  $strict = false 是否严格匹配(值和类型)
  • htmlEncode($data, $valuesOnly = true, $charset = null)     Encodes(编码) special characters(字符) in an array of strings into HTML entities(实体)   编码在数组中的特殊的字符转成html 实体 $valuesOnly = true (是否只是值转化为html实体,默认是true)
  • htmlDecode($data, $valuesOnly = true)  Decodes(解码) HTML entities(实体) into the corresponding(相应的) characters(字符) in an array of strings. $valuesOnly = true(是否只有值解码 ,默认是true)
  • multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR) 数组排序
posted @ 2017-02-09 17:35  哦先生  阅读(2928)  评论(0编辑  收藏  举报