1 關注者 (follower)

類別 yii\helpers\ArrayHelper (Class yii\helpers\ArrayHelper)

繼承 (Inheritance)yii\helpers\ArrayHelper » yii\helpers\BaseArrayHelper
自版本 (Available since version)2.0
原始碼 (Source Code) https://github.com/yiisoft/yii2/blob/master/framework/helpers/ArrayHelper.php

ArrayHelper 提供了您可以在應用程式中使用的額外陣列功能。(ArrayHelper provides additional array functionality that you can use in your application.)

有關 ArrayHelper 的更多詳細資訊和使用方法,請參閱關於陣列輔助方法的指南文章 (guide article on array helpers)。(For more details and usage information on ArrayHelper, see the guide article on array helpers.)

公開方法 (Public Methods)

隱藏繼承的方法 (Hide inherited methods)

方法 (Method) 描述 (Description) 定義於 (Defined By)
filter() 根據指定的規則過濾陣列。(Filters array according to rules specified.) yii\helpers\BaseArrayHelper
getColumn() 傳回陣列中指定欄位的值。(Returns the values of a specified column in an array.) yii\helpers\BaseArrayHelper
getValue() 使用給定的鍵或屬性名稱,檢索陣列元素或物件屬性的值。(Retrieves the value of an array element or object property with the given key or property name.) yii\helpers\BaseArrayHelper
htmlDecode() 將 HTML 實體解碼為字串陣列中的對應字元。(Decodes HTML entities into the corresponding characters in an array of strings.) yii\helpers\BaseArrayHelper
htmlEncode() 將字串陣列中的特殊字元編碼為 HTML 實體。(Encodes special characters in an array of strings into HTML entities.) yii\helpers\BaseArrayHelper
index() 根據指定的鍵索引和/或分組陣列。(Indexes and/or groups the array according to a specified key.) yii\helpers\BaseArrayHelper
isAssociative() 傳回一個值,指示給定的陣列是否為關聯陣列。(Returns a value indicating whether the given array is an associative array.) yii\helpers\BaseArrayHelper
isIn() 檢查陣列或 Traversable 是否包含元素。(Check whether an array or Traversable contains an element.) yii\helpers\BaseArrayHelper
isIndexed() 傳回一個值,指示給定的陣列是否為索引陣列。(Returns a value indicating whether the given array is an indexed array.) yii\helpers\BaseArrayHelper
isSubset() 檢查陣列或 Traversable 是否為另一個陣列或 Traversable 的子集。(Checks whether an array or Traversable is a subset of another array or Traversable.) yii\helpers\BaseArrayHelper
isTraversable() 檢查變數是否為陣列或 Traversable。(Checks whether a variable is an array or Traversable.) yii\helpers\BaseArrayHelper
keyExists() 檢查給定的陣列是否包含指定的鍵。(Checks if the given array contains the specified key.) yii\helpers\BaseArrayHelper
map() 從多維陣列或物件陣列建立地圖(鍵值對)。(Builds a map (key-value pairs) from a multidimensional array or an array of objects.) yii\helpers\BaseArrayHelper
merge() 遞迴地將兩個或多個陣列合併為一個。(Merges two or more arrays into one recursively.) yii\helpers\BaseArrayHelper
multisort() 依一個或多個鍵對物件或陣列(具有相同結構)的陣列進行排序。(Sorts an array of objects or arrays (with the same structure) by one or several keys.) yii\helpers\BaseArrayHelper
recursiveSort() 遞迴地排序陣列。(Sorts array recursively.) yii\helpers\BaseArrayHelper
remove() 從陣列中移除項目並傳回值。如果鍵在陣列中不存在,則會傳回預設值。(Removes an item from an array and returns the value. If the key does not exist in the array, the default value will be returned instead.) yii\helpers\BaseArrayHelper
removeValue() 從陣列中移除具有相符值的項目,並傳回已移除的項目。(Removes items with matching values from the array and returns the removed items.) yii\helpers\BaseArrayHelper
setValue() 在指定的鍵路徑將值寫入關聯陣列。(Writes a value into an associative array at the key path specified.) yii\helpers\BaseArrayHelper
toArray() 將物件或物件陣列轉換為陣列。(Converts an object or an array of objects into an array.) yii\helpers\BaseArrayHelper

方法詳情 (Method Details)

隱藏繼承的方法 (Hide inherited methods)

filter() public static method (自版本 2.0.9 起可用) (available since version 2.0.9)

定義於: yii\helpers\BaseArrayHelper::filter() (Defined in: yii\helpers\BaseArrayHelper::filter())

根據指定的規則過濾陣列。(Filters array according to rules specified.)

例如 (For example)

$array = [
    'A' => [1, 2],
    'B' => [
        'C' => 1,
        'D' => 2,
    ],
    'E' => 1,
];

$result = \yii\helpers\ArrayHelper::filter($array, ['A']);
// $result will be:
// [
//     'A' => [1, 2],
// ]

$result = \yii\helpers\ArrayHelper::filter($array, ['A', 'B.C']);
// $result will be:
// [
//     'A' => [1, 2],
//     'B' => ['C' => 1],
// ]

$result = \yii\helpers\ArrayHelper::filter($array, ['B', '!B.C']);
// $result will be:
// [
//     'B' => ['D' => 2],
// ]
public static array filter ( $array, $filters )
$array array

來源陣列 (Source array)

$filters iterable

定義應保留或從結果中移除的陣列鍵的規則。每個規則為 (Rules that define array keys which should be left or removed from results. Each rule is)

  • var - $array['var'] 將保留在結果中。(var - $array['var'] will be left in result.)
  • var.key = 只有 `$array['var']['key'] 將保留在結果中。(var.key = only `$array['var']['key'] will be left in result.)
  • !var.key = `$array['var']['key'] 將從結果中移除。(!var.key = `$array['var']['key'] will be removed from result.)
return array

已過濾陣列 (Filtered array)

                public static function filter($array, $filters)
{
    $result = [];
    $excludeFilters = [];
    foreach ($filters as $filter) {
        if (!is_string($filter) && !is_int($filter)) {
            continue;
        }
        if (is_string($filter) && strncmp($filter, '!', 1) === 0) {
            $excludeFilters[] = substr($filter, 1);
            continue;
        }
        $nodeValue = $array; //set $array as root node
        $keys = explode('.', (string) $filter);
        foreach ($keys as $key) {
            if (!array_key_exists($key, $nodeValue)) {
                continue 2; //Jump to next filter
            }
            $nodeValue = $nodeValue[$key];
        }
        //We've found a value now let's insert it
        $resultNode = &$result;
        foreach ($keys as $key) {
            if (!array_key_exists($key, $resultNode)) {
                $resultNode[$key] = [];
            }
            $resultNode = &$resultNode[$key];
        }
        $resultNode = $nodeValue;
    }
    foreach ($excludeFilters as $filter) {
        $excludeNode = &$result;
        $keys = explode('.', (string) $filter);
        $numNestedKeys = count($keys) - 1;
        foreach ($keys as $i => $key) {
            if (!array_key_exists($key, $excludeNode)) {
                continue 2; //Jump to next filter
            }
            if ($i < $numNestedKeys) {
                $excludeNode = &$excludeNode[$key];
            } else {
                unset($excludeNode[$key]);
                break;
            }
        }
    }
    return $result;
}

            
getColumn() public static method

定義於: yii\helpers\BaseArrayHelper::getColumn() (Defined in: yii\helpers\BaseArrayHelper::getColumn())

傳回陣列中指定欄位的值。(Returns the values of a specified column in an array.)

輸入陣列應為多維陣列或物件陣列。(The input array should be multidimensional or an array of objects.)

例如, (For example,)

$array = [
    ['id' => '123', 'data' => 'abc'],
    ['id' => '345', 'data' => 'def'],
];
$result = ArrayHelper::getColumn($array, 'id');
// the result is: ['123', '345']

// using anonymous function
$result = ArrayHelper::getColumn($array, function ($element) {
    return $element['id'];
});
public static array getColumn ( $array, $name, $keepKeys true )
$array array
$name integer|string|array|Closure
$keepKeys boolean

是否保持陣列鍵。如果為 false,則結果陣列將使用整數重新索引。(Whether to maintain the array keys. If false, the resulting array will be re-indexed with integers.)

return array

欄位值的列表 (The list of column values)

                public static function getColumn($array, $name, $keepKeys = true)
{
    $result = [];
    if ($keepKeys) {
        foreach ($array as $k => $element) {
            $result[$k] = static::getValue($element, $name);
        }
    } else {
        foreach ($array as $element) {
            $result[] = static::getValue($element, $name);
        }
    }
    return $result;
}

            
getValue() public static method

定義於: yii\helpers\BaseArrayHelper::getValue() (Defined in: yii\helpers\BaseArrayHelper::getValue())

使用給定的鍵或屬性名稱,檢索陣列元素或物件屬性的值。(Retrieves the value of an array element or object property with the given key or property name.)

如果陣列中不存在該鍵,則會改為傳回預設值。從物件取值時不適用。

可以使用點分隔格式指定鍵,以檢索子陣列的值或嵌入物件的屬性。 特別是,如果鍵為 x.y.z,則傳回值將為 $array['x']['y']['z']$array->x->y->z (如果 $array 是物件)。 如果 $array['x']$array->x 既不是陣列也不是物件,則會傳回預設值。 請注意,如果陣列已經有一個元素 x.y.z,那麼將傳回它的值,而不是遍歷子陣列。 因此,最好指定像 ['x', 'y', 'z'] 這樣的鍵名陣列。

以下是一些使用範例:

// working with array
$username = \yii\helpers\ArrayHelper::getValue($_POST, 'username');
// working with object
$username = \yii\helpers\ArrayHelper::getValue($user, 'username');
// working with anonymous function
$fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) {
    return $user->firstName . ' ' . $user->lastName;
});
// using dot format to retrieve the property of embedded object
$street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
// using an array of keys to retrieve the value
$value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
public static mixed getValue ( $array, $key, $default null )
$array array|object

從中提取值的陣列或物件

$key string|Closure|array

陣列元素的鍵名、鍵的陣列或物件的屬性名稱,或傳回值的匿名函式。 匿名函式簽章應為:function($array, $defaultValue)。 自 2.0.4 版本起,可以使用傳遞鍵陣列的功能。

$default mixed

如果指定的陣列鍵不存在,則傳回的預設值。 從物件取值時不適用。

return mixed

如果找到元素則傳回元素的值,否則傳回預設值

                public static function getValue($array, $key, $default = null)
{
    if ($key instanceof \Closure) {
        return $key($array, $default);
    }
    if (is_array($key)) {
        $lastKey = array_pop($key);
        foreach ($key as $keyPart) {
            $array = static::getValue($array, $keyPart);
        }
        $key = $lastKey;
    }
    if (is_object($array) && property_exists($array, $key)) {
        return $array->$key;
    }
    if (static::keyExists($key, $array)) {
        return $array[$key];
    }
    if ($key && ($pos = strrpos($key, '.')) !== false) {
        $array = static::getValue($array, substr($key, 0, $pos), $default);
        $key = substr($key, $pos + 1);
    }
    if (static::keyExists($key, $array)) {
        return $array[$key];
    }
    if (is_object($array)) {
        // this is expected to fail if the property does not exist, or __get() is not implemented
        // it is not reliably possible to check whether a property is accessible beforehand
        try {
            return $array->$key;
        } catch (\Exception $e) {
            if ($array instanceof ArrayAccess) {
                return $default;
            }
            throw $e;
        }
    }
    return $default;
}

            
htmlDecode() public static method

定義於: yii\helpers\BaseArrayHelper::htmlDecode()

將 HTML 實體解碼為字串陣列中的對應字元。(Decodes HTML entities into the corresponding characters in an array of strings.)

預設情況下,只會解碼陣列值。 如果值是陣列,此方法也會遞迴地解碼它。 只會解碼字串值。

另請參閱 https://php.dev.org.tw/manual/en/function.htmlspecialchars-decode.php

public static array htmlDecode ( $data, $valuesOnly true )
$data array

要解碼的資料

$valuesOnly boolean

是否僅解碼陣列值。 如果為 false,則陣列鍵和陣列值都將被解碼。

return array

已解碼的資料

                public static function htmlDecode($data, $valuesOnly = true)
{
    $d = [];
    foreach ($data as $key => $value) {
        if (!$valuesOnly && is_string($key)) {
            $key = htmlspecialchars_decode($key, ENT_QUOTES | ENT_SUBSTITUTE);
        }
        if (is_string($value)) {
            $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES | ENT_SUBSTITUTE);
        } elseif (is_array($value)) {
            $d[$key] = static::htmlDecode($value, $valuesOnly);
        } else {
            $d[$key] = $value;
        }
    }
    return $d;
}

            
htmlEncode() public static method

定義於: yii\helpers\BaseArrayHelper::htmlEncode()

將字串陣列中的特殊字元編碼為 HTML 實體。(Encodes special characters in an array of strings into HTML entities.)

預設情況下,只會編碼陣列值。 如果值是陣列,此方法也會遞迴地編碼它。 只會編碼字串值。

另請參閱 https://php.dev.org.tw/manual/en/function.htmlspecialchars.php

public static array htmlEncode ( $data, $valuesOnly true, $charset null )
$data array

$data

$valuesOnly boolean

要編碼的資料

$charset string|null

資料使用的字元集。 如果未設定,將使用 yii\base\Application::$charset

return array

已編碼的資料

                public static function htmlEncode($data, $valuesOnly = true, $charset = null)
{
    if ($charset === null) {
        $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
    }
    $d = [];
    foreach ($data as $key => $value) {
        if (!$valuesOnly && is_string($key)) {
            $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
        }
        if (is_string($value)) {
            $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
        } elseif (is_array($value)) {
            $d[$key] = static::htmlEncode($value, $valuesOnly, $charset);
        } else {
            $d[$key] = $value;
        }
    }
    return $d;
}

            
index() public static method

定義於: yii\helpers\BaseArrayHelper::index()

根據指定的鍵索引和/或分組陣列。(Indexes and/or groups the array according to a specified key.)

輸入應該是多維陣列或物件陣列。

$key 可以是子陣列的鍵名、物件的屬性名稱,或是必須傳回將用作鍵的值的匿名函式。

$groups 是一個鍵的陣列,將用於根據指定的鍵將輸入陣列分組為一個或多個子陣列。

如果 $key 指定為 null,或與鍵對應的元素值為 null,且未指定 $groups,則該元素將被捨棄。

例如 (For example)

$array = [
    ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
    ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
    ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
];
$result = ArrayHelper::index($array, 'id');

結果將是一個關聯陣列,其中鍵是 id 屬性的值

[
    '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
    '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
    // The second element of an original array is overwritten by the last element because of the same id
]

匿名函式也可以在分組陣列中使用。

$result = ArrayHelper::index($array, function ($element) {
    return $element['id'];
});

id 作為第三個引數傳遞,將依 id 分組 $array

$result = ArrayHelper::index($array, null, 'id');

結果將是一個多維陣列,第一層依 id 分組,第二層依 device 分組,第三層依 data 索引

[
    '123' => [
        ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
    ],
    '345' => [ // all elements with this index are present in the result array
        ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
        ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
    ]
]

匿名函式也可以在分組鍵的陣列中使用

$result = ArrayHelper::index($array, 'data', [function ($element) {
    return $element['id'];
}, 'device']);

結果將是一個多維陣列,第一層依 id 分組,第二層依 device 分組,第三層依 data 索引

[
    '123' => [
        'laptop' => [
            'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
        ]
    ],
    '345' => [
        'tablet' => [
            'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
        ],
        'smartphone' => [
            'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
        ]
    ]
]
public static array index ( $array, $key, $groups = [] )
$array array

需要索引或分組的陣列

$key string|Closure|null

欄位名稱或匿名函式,其結果將用於索引陣列

$groups string|string[]|Closure[]|null

鍵的陣列,將用於依一個或多個鍵分組輸入陣列。 如果 $key 屬性或其特定元素的值為 null,且未定義 $groups,則將捨棄陣列元素。 否則,如果指定了 $groups,則陣列元素將被添加到結果陣列中,而沒有任何鍵。 此參數自 2.0.8 版本起可用。

return array

已索引和/或分組的陣列

                public static function index($array, $key, $groups = [])
{
    $result = [];
    $groups = (array) $groups;
    foreach ($array as $element) {
        $lastArray = &$result;
        foreach ($groups as $group) {
            $value = static::getValue($element, $group);
            if (!array_key_exists($value, $lastArray)) {
                $lastArray[$value] = [];
            }
            $lastArray = &$lastArray[$value];
        }
        if ($key === null) {
            if (!empty($groups)) {
                $lastArray[] = $element;
            }
        } else {
            $value = static::getValue($element, $key);
            if ($value !== null) {
                if (is_float($value)) {
                    $value = StringHelper::floatToString($value);
                }
                $lastArray[$value] = $element;
            }
        }
        unset($lastArray);
    }
    return $result;
}

            
isAssociative() public static method

定義於: yii\helpers\BaseArrayHelper::isAssociative()

傳回一個值,指示給定的陣列是否為關聯陣列。(Returns a value indicating whether the given array is an associative array.)

如果陣列的所有鍵都是字串,則該陣列是關聯陣列。 如果 $allStrings 為 false,則如果陣列的鍵中至少有一個是字串,則該陣列將被視為關聯陣列。

請注意,空陣列將不被視為關聯陣列。

public static boolean isAssociative ( $array, $allStrings true )
$array array

正在檢查的陣列

$allStrings boolean

為了將陣列視為關聯陣列,是否陣列鍵必須全部為字串。

return boolean

陣列是否為關聯陣列

                public static function isAssociative($array, $allStrings = true)
{
    if (empty($array) || !is_array($array)) {
        return false;
    }
    if ($allStrings) {
        foreach ($array as $key => $value) {
            if (!is_string($key)) {
                return false;
            }
        }
        return true;
    }
    foreach ($array as $key => $value) {
        if (is_string($key)) {
            return true;
        }
    }
    return false;
}

            
isIn() public static method (available since version 2.0.7)

定義於: yii\helpers\BaseArrayHelper::isIn()

檢查陣列或 Traversable 是否包含元素。(Check whether an array or Traversable contains an element.)

此方法的功能與 PHP 函式 in_array() 相同,但另外適用於實作 Traversable 介面的物件。

另請參閱 https://php.dev.org.tw/manual/en/function.in-array.php

public static boolean isIn ( $needle, $haystack, $strict false )
$needle mixed

要尋找的值。

$haystack iterable

要搜尋的值集合。

$strict boolean

是否啟用嚴格 (===) 比較。

return boolean

如果在 $haystack 中找到 $needle,則為 true,否則為 false

throws yii\base\InvalidArgumentException

如果 $haystack 既不是可遍歷的也不是陣列。

                public static function isIn($needle, $haystack, $strict = false)
{
    if (!static::isTraversable($haystack)) {
        throw new InvalidArgumentException('Argument $haystack must be an array or implement Traversable');
    }
    if (is_array($haystack)) {
        return in_array($needle, $haystack, $strict);
    }
    foreach ($haystack as $value) {
        if ($strict ? $needle === $value : $needle == $value) {
            return true;
        }
    }
    return false;
}

            
isIndexed() public static method

定義於: yii\helpers\BaseArrayHelper::isIndexed()

傳回一個值,指示給定的陣列是否為索引陣列。(Returns a value indicating whether the given array is an indexed array.)

如果陣列的所有鍵都是整數,則該陣列是索引陣列。 如果 $consecutive 為 true,則陣列鍵必須是從 0 開始的連續序列。

請注意,空陣列將被視為索引陣列。

public static boolean isIndexed ( $array, $consecutive false )
$array array

正在檢查的陣列

$consecutive boolean

為了將陣列視為索引陣列,是否陣列鍵必須是連續序列。

return boolean

陣列是否為索引陣列

                public static function isIndexed($array, $consecutive = false)
{
    if (!is_array($array)) {
        return false;
    }
    if (empty($array)) {
        return true;
    }
    $keys = array_keys($array);
    if ($consecutive) {
        return $keys === array_keys($keys);
    }
    foreach ($keys as $key) {
        if (!is_int($key)) {
            return false;
        }
    }
    return true;
}

            
isSubset() public static method (available since version 2.0.7)

定義於: yii\helpers\BaseArrayHelper::isSubset()

檢查陣列或 Traversable 是否為另一個陣列或 Traversable 的子集。(Checks whether an array or Traversable is a subset of another array or Traversable.)

如果 $needles 的所有元素都包含在 $haystack 中,此方法將傳回 true。 如果至少遺失一個元素,將傳回 false

public static boolean isSubset ( $needles, $haystack, $strict false )
$needles iterable

必須全部$haystack 中的值。

$haystack iterable

要搜尋的值集合。

$strict boolean

是否啟用嚴格 (===) 比較。

return boolean

如果 $needles$haystack 的子集,則為 true,否則為 false

throws yii\base\InvalidArgumentException

如果 $haystack$needles 既不是可遍歷的也不是陣列。

                public static function isSubset($needles, $haystack, $strict = false)
{
    if (!static::isTraversable($needles)) {
        throw new InvalidArgumentException('Argument $needles must be an array or implement Traversable');
    }
    foreach ($needles as $needle) {
        if (!static::isIn($needle, $haystack, $strict)) {
            return false;
        }
    }
    return true;
}

            
isTraversable() public static method (available since version 2.0.8)

定義於: yii\helpers\BaseArrayHelper::isTraversable()

檢查變數是否為陣列或 Traversable。(Checks whether a variable is an array or Traversable.)

此方法的功能與 PHP 函式 is_array() 相同,但另外適用於實作 Traversable 介面的物件。

另請參閱 https://php.dev.org.tw/manual/en/function.is-array.php

public static boolean isTraversable ( $var )
$var mixed

正在評估的變數。

return boolean

$var 是否可以透過 foreach 遍歷

                public static function isTraversable($var)
{
    return is_array($var) || $var instanceof Traversable;
}

            
keyExists() public static method

定義於: yii\helpers\BaseArrayHelper::keyExists()

檢查給定的陣列是否包含指定的鍵。(Checks if the given array contains the specified key.)

此方法增強了 array_key_exists() 函式,使其支援不區分大小寫的鍵比較。

public static boolean keyExists ( $key, $array, $caseSensitive true )
$key string|integer

要檢查的鍵

$array array|ArrayAccess

要檢查鍵的陣列

$caseSensitive boolean

鍵比較是否應區分大小寫

return boolean

陣列是否包含指定的鍵

                public static function keyExists($key, $array, $caseSensitive = true)
{
    // ToDo: This check can be removed when the minimum PHP version is >= 8.1 (Yii2.2)
    if (is_float($key)) {
        $key = (int)$key;
    }
    if ($caseSensitive) {
        if (is_array($array) && array_key_exists($key, $array)) {
            return true;
        }
        // Cannot use `array_has_key` on Objects for PHP 7.4+, therefore we need to check using [[ArrayAccess::offsetExists()]]
        return $array instanceof ArrayAccess && $array->offsetExists($key);
    }
    if ($array instanceof ArrayAccess) {
        throw new InvalidArgumentException('Second parameter($array) cannot be ArrayAccess in case insensitive mode');
    }
    foreach (array_keys($array) as $k) {
        if (strcasecmp($key, $k) === 0) {
            return true;
        }
    }
    return false;
}

            
map() public static method

定義於: yii\helpers\BaseArrayHelper::map()

從多維陣列或物件陣列建立地圖(鍵值對)。(Builds a map (key-value pairs) from a multidimensional array or an array of objects.)

$from$to 參數指定要設定對應的鍵名或屬性名稱。 選擇性地,可以根據分組欄位 $group 進一步對應進行分組。

例如, (For example,)

$array = [
    ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
    ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
    ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
];

$result = ArrayHelper::map($array, 'id', 'name');
// the result is:
// [
//     '123' => 'aaa',
//     '124' => 'bbb',
//     '345' => 'ccc',
// ]

$result = ArrayHelper::map($array, 'id', 'name', 'class');
// the result is:
// [
//     'x' => [
//         '123' => 'aaa',
//         '124' => 'bbb',
//     ],
//     'y' => [
//         '345' => 'ccc',
//     ],
// ]
public static array map ( $array, $from, $to, $group null )
$array array
$from string|Closure
$to string|Closure
$group string|Closure|null

                public static function map($array, $from, $to, $group = null)
{
    $result = [];
    foreach ($array as $element) {
        $key = static::getValue($element, $from);
        $value = static::getValue($element, $to);
        if ($group !== null) {
            $result[static::getValue($element, $group)][$key] = $value;
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

            
merge() public static method

定義於: yii\helpers\BaseArrayHelper::merge()

遞迴地將兩個或多個陣列合併為一個。(Merges two or more arrays into one recursively.)

如果每個陣列都有一個具有相同字串鍵值的元素,則後者將覆寫前者 (與 array_merge_recursive 不同)。 如果兩個陣列都有陣列類型元素且具有相同的鍵,則將進行遞迴合併。 對於整數鍵元素,後一個陣列的元素將附加到前一個陣列。 您可以使用 yii\helpers\UnsetArrayValue 物件從先前的陣列中取消設定值,或使用 yii\helpers\ReplaceArrayValue 強制取代先前的值而不是遞迴合併。

public static array merge ( $a, $b )
$a array

要合併到的陣列

$b array

要從中合併的陣列。 您可以透過第三個引數、第四個引數等指定其他陣列。

return array

合併後的陣列 (原始陣列未更改。)

                public static function merge($a, $b)
{
    $args = func_get_args();
    $res = array_shift($args);
    while (!empty($args)) {
        foreach (array_shift($args) as $k => $v) {
            if ($v instanceof UnsetArrayValue) {
                unset($res[$k]);
            } elseif ($v instanceof ReplaceArrayValue) {
                $res[$k] = $v->value;
            } elseif (is_int($k)) {
                if (array_key_exists($k, $res)) {
                    $res[] = $v;
                } else {
                    $res[$k] = $v;
                }
            } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
                $res[$k] = static::merge($res[$k], $v);
            } else {
                $res[$k] = $v;
            }
        }
    }
    return $res;
}

            
multisort() public static method

定義於: yii\helpers\BaseArrayHelper::multisort()

依一個或多個鍵對物件或陣列(具有相同結構)的陣列進行排序。(Sorts an array of objects or arrays (with the same structure) by one or several keys.)

public static void multisort ( &$array, $key, $direction SORT_ASC, $sortFlag SORT_REGULAR )
$array array

要排序的陣列。 呼叫此方法後,陣列將被修改。

$key string|Closure|array

要依其排序的鍵。 這指的是子陣列元素的鍵名、物件的屬性名稱,或傳回用於比較目的的值的匿名函式。 匿名函式簽章應為:function($item)。 若要依多個鍵排序,請在此處提供鍵陣列。

$direction integer|array

排序方向。 它可以是 SORT_ASCSORT_DESC。 當依具有不同排序方向的多個鍵排序時,請使用排序方向陣列。

$sortFlag integer|array

PHP 排序旗標。 有效值包括 SORT_REGULARSORT_NUMERICSORT_STRINGSORT_LOCALE_STRINGSORT_NATURALSORT_FLAG_CASE。 請參閱 PHP 手冊 以取得更多詳細資訊。 當依具有不同排序旗標的多個鍵排序時,請使用排序旗標陣列。

throws yii\base\InvalidArgumentException

如果 $direction 或 $sortFlag 參數的元素數量與 $key 的元素數量不符。

                public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
{
    $keys = is_array($key) ? $key : [$key];
    if (empty($keys) || empty($array)) {
        return;
    }
    $n = count($keys);
    if (is_scalar($direction)) {
        $direction = array_fill(0, $n, $direction);
    } elseif (count($direction) !== $n) {
        throw new InvalidArgumentException('The length of $direction parameter must be the same as that of $keys.');
    }
    if (is_scalar($sortFlag)) {
        $sortFlag = array_fill(0, $n, $sortFlag);
    } elseif (count($sortFlag) !== $n) {
        throw new InvalidArgumentException('The length of $sortFlag parameter must be the same as that of $keys.');
    }
    $args = [];
    foreach ($keys as $i => $k) {
        $flag = $sortFlag[$i];
        $args[] = static::getColumn($array, $k);
        $args[] = $direction[$i];
        $args[] = $flag;
    }
    // This fix is used for cases when main sorting specified by columns has equal values
    // Without it it will lead to Fatal Error: Nesting level too deep - recursive dependency?
    $args[] = range(1, count($array));
    $args[] = SORT_ASC;
    $args[] = SORT_NUMERIC;
    $args[] = &$array;
    call_user_func_array('array_multisort', $args);
}

            
recursiveSort() public static method

定義於: yii\helpers\BaseArrayHelper::recursiveSort()

遞迴地排序陣列。(Sorts array recursively.)

public static array recursiveSort ( array &$array, $sorter null )
$array array

透過參考傳遞的陣列。

$sorter callable|null

陣列排序器。 如果省略,則依值排序索引陣列,依鍵排序關聯陣列。

                public static function recursiveSort(array &$array, $sorter = null)
{
    foreach ($array as &$value) {
        if (is_array($value)) {
            static::recursiveSort($value, $sorter);
        }
    }
    unset($value);
    if ($sorter === null) {
        $sorter = static::isIndexed($array) ? 'sort' : 'ksort';
    }
    call_user_func_array($sorter, [&$array]);
    return $array;
}

            
remove() public static method

定義於: yii\helpers\BaseArrayHelper::remove()

從陣列中移除項目並傳回值。如果鍵在陣列中不存在,則會傳回預設值。(Removes an item from an array and returns the value. If the key does not exist in the array, the default value will be returned instead.)

使用範例:

// $array = ['type' => 'A', 'options' => [1, 2]];
// working with array
$type = \yii\helpers\ArrayHelper::remove($array, 'type');
// $array content
// $array = ['options' => [1, 2]];
public static mixed|null remove ( &$array, $key, $default null )
$array array

要從中提取值的陣列

$key string

陣列元素的鍵名

$default mixed

如果指定的鍵不存在,則傳回的預設值

return mixed|null

如果找到元素則傳回元素的值,否則傳回預設值

                public static function remove(&$array, $key, $default = null)
{
    // ToDo: This check can be removed when the minimum PHP version is >= 8.1 (Yii2.2)
    if (is_float($key)) {
        $key = (int)$key;
    }
    if (is_array($array) && array_key_exists($key, $array)) {
        $value = $array[$key];
        unset($array[$key]);
        return $value;
    }
    return $default;
}

            
removeValue() public static method (available since version 2.0.11)

定義於: yii\helpers\BaseArrayHelper::removeValue()

從陣列中移除具有相符值的項目,並傳回已移除的項目。(Removes items with matching values from the array and returns the removed items.)

範例:

$array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
$removed = \yii\helpers\ArrayHelper::removeValue($array, 'Jackson');
// result:
// $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
// $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
public static array removeValue ( &$array, $value )
$array array

要從中尋找值的陣列

$value mixed

要從陣列中移除的值

return array

從陣列中移除的項目

                public static function removeValue(&$array, $value)
{
    $result = [];
    if (is_array($array)) {
        foreach ($array as $key => $val) {
            if ($val === $value) {
                $result[$key] = $val;
                unset($array[$key]);
            }
        }
    }
    return $result;
}

            
setValue() public static method (available since version 2.0.13)

定義於: yii\helpers\BaseArrayHelper::setValue()

在指定的鍵路徑將值寫入關聯陣列。(Writes a value into an associative array at the key path specified.)

如果尚無此鍵路徑,將遞迴建立它。 如果鍵存在,它將被覆寫。

 $array = [
     'key' => [
         'in' => [
             'val1',
             'key' => 'val'
         ]
     ]
 ];

ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']); 的結果將如下所示

 [
     'key' => [
         'in' => [
             ['arr' => 'val'],
             'key' => 'val'
         ]
     ]
 ]

ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']); 的結果將如下所示

 [
     'key' => [
         'in' => [
             'arr' => 'val'
         ]
     ]
 ]
public static void setValue ( &$array, $path, $value )
$array array

要將值寫入的陣列

$path string|array|null

您要將值寫入 $array 的路徑,路徑可以由字串描述,其中每個鍵應以點分隔,如果路徑為 null,您也可以將路徑描述為鍵的陣列,則 $array 將被賦予 $value

$value mixed

要寫入的值

                public static function setValue(&$array, $path, $value)
{
    if ($path === null) {
        $array = $value;
        return;
    }
    $keys = is_array($path) ? $path : explode('.', $path);
    while (count($keys) > 1) {
        $key = array_shift($keys);
        if (!isset($array[$key])) {
            $array[$key] = [];
        }
        if (!is_array($array[$key])) {
            $array[$key] = [$array[$key]];
        }
        $array = &$array[$key];
    }
    $array[array_shift($keys)] = $value;
}

            
toArray() public static method

定義於: yii\helpers\BaseArrayHelper::toArray()

將物件或物件陣列轉換為陣列。(Converts an object or an array of objects into an array.)

public static array toArray ( $object, $properties = [], $recursive true )
$object object|array|string

要轉換為陣列的物件

$properties array

從物件類別名稱到需要放入結果陣列的屬性的對應。 為每個類別指定的屬性是以下格式的陣列

[
    'app\models\Post' => [
        'id',
        'title',
        // the key name in array result => property name
        'createTime' => 'created_at',
        // the key name in array result => anonymous function
        'length' => function ($post) {
            return strlen($post->content);
        },
    ],
]

ArrayHelper::toArray($post, $properties) 的結果可能如下所示

[
    'id' => 123,
    'title' => 'test',
    'createTime' => '2013-01-01 12:00AM',
    'length' => 301,
]
$recursive boolean

是否遞迴地將作為物件的屬性轉換為陣列。

return array

物件的陣列表示形式

                public static function toArray($object, $properties = [], $recursive = true)
{
    if (is_array($object)) {
        if ($recursive) {
            foreach ($object as $key => $value) {
                if (is_array($value) || is_object($value)) {
                    $object[$key] = static::toArray($value, $properties, true);
                }
            }
        }
        return $object;
    } elseif ($object instanceof \DateTimeInterface) {
        return (array)$object;
    } elseif (is_object($object)) {
        if (!empty($properties)) {
            $className = get_class($object);
            if (!empty($properties[$className])) {
                $result = [];
                foreach ($properties[$className] as $key => $name) {
                    if (is_int($key)) {
                        $result[$name] = $object->$name;
                    } else {
                        $result[$key] = static::getValue($object, $name);
                    }
                }
                return $recursive ? static::toArray($result, $properties) : $result;
            }
        }
        if ($object instanceof Arrayable) {
            $result = $object->toArray([], [], $recursive);
        } else {
            $result = [];
            foreach ($object as $key => $value) {
                $result[$key] = $value;
            }
        }
        return $recursive ? static::toArray($result, $properties) : $result;
    }
    return [$object];
}