Yii2 yii\helpers\ArrayHelper

yii\helpers\ArrayHelper 是一個數組輔助類,提供額外的數組功能函數php

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

Converts an object or an array of objects into an array (把對象、數組、字符串安裝條件從新轉換成數組)html

源代碼中的例子:數組

 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])};app

 UnsetArrayValue   yii\helpers\UnsetArrayValue  類註釋能夠看出具體做用yii

/**
 * 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類註釋能夠看出具體做用post

 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)  根據數組的鍵獲取數組元素的值或者根據對象的屬性名稱或者對象的屬性值ui

 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) 數組排序
相關文章
相關標籤/搜索