0 追蹤者

類別 yii\helpers\BaseArrayHelper

繼承關係yii\helpers\BaseArrayHelper
子類別yii\helpers\ArrayHelper
可用版本自2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseArrayHelper.php

BaseArrayHelper 為 yii\helpers\ArrayHelper 提供了具體實作。

請勿使用 BaseArrayHelper。請改用 yii\helpers\ArrayHelper

公共方法

隱藏繼承的方法

方法 描述 定義於
filter() 根據指定的規則篩選陣列。 yii\helpers\BaseArrayHelper
getColumn() 傳回陣列中指定欄位的值。 yii\helpers\BaseArrayHelper
getValue() 使用給定的鍵或屬性名稱,檢索陣列元素或物件屬性的值。 yii\helpers\BaseArrayHelper
htmlDecode() 將字串陣列中的 HTML 實體解碼為對應的字元。 yii\helpers\BaseArrayHelper
htmlEncode() 將字串陣列中的特殊字元編碼為 HTML 實體。 yii\helpers\BaseArrayHelper
index() 根據指定的鍵索引和/或分組陣列。 yii\helpers\BaseArrayHelper
isAssociative() 傳回一個值,指示給定的陣列是否為關聯陣列。 yii\helpers\BaseArrayHelper
isIn() 檢查陣列或 Traversable 是否包含元素。 yii\helpers\BaseArrayHelper
isIndexed() 傳回一個值,指示給定的陣列是否為索引陣列。 yii\helpers\BaseArrayHelper
isSubset() 檢查陣列或 Traversable 是否為另一個陣列或 Traversable 的子集。 yii\helpers\BaseArrayHelper
isTraversable() 檢查變數是否為陣列或 Traversable yii\helpers\BaseArrayHelper
keyExists() 檢查給定的陣列是否包含指定的鍵。 yii\helpers\BaseArrayHelper
map() 從多維陣列或物件陣列建立映射(鍵值對)。 yii\helpers\BaseArrayHelper
merge() 將兩個或多個陣列遞迴合併為一個。 yii\helpers\BaseArrayHelper
multisort() 依據一個或多個鍵對物件陣列或陣列(具有相同結構)進行排序。 yii\helpers\BaseArrayHelper
recursiveSort() 遞迴排序陣列。 yii\helpers\BaseArrayHelper
remove() 從陣列中移除一個項目並傳回該值。如果鍵在陣列中不存在,則會傳回預設值。 yii\helpers\BaseArrayHelper
removeValue() 從陣列中移除具有匹配值的項目,並傳回已移除的項目。 yii\helpers\BaseArrayHelper
setValue() 將值寫入指定鍵路徑的關聯陣列中。 yii\helpers\BaseArrayHelper
toArray() 將物件或物件陣列轉換為陣列。 yii\helpers\BaseArrayHelper

方法詳情

隱藏繼承的方法

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

根據指定的規則篩選陣列。

範例

$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

來源陣列

$filters iterable

定義應保留或從結果中移除的陣列鍵的規則。每個規則為

  • var - $array['var'] 將保留在結果中。
  • var.key = 只有 `$array['var']['key'] 將保留在結果中。
  • !var.key = `$array['var']['key'] 將從結果中移除。
return 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

傳回陣列中指定欄位的值。

輸入陣列應為多維陣列或物件陣列。

範例,

$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,則結果陣列將以整數重新索引。

return array

欄位值的列表

                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

使用給定的鍵或屬性名稱,檢索陣列元素或物件屬性的值。

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

鍵可以使用點格式指定,以檢索子陣列的值或嵌入物件的屬性。特別是,如果鍵為 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

將字串陣列中的 HTML 實體解碼為對應的字元。

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

另請參閱 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

將字串陣列中的特殊字元編碼為 HTML 實體。

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

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

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

要編碼的資料

$valuesOnly boolean

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

$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

根據指定的鍵索引和/或分組陣列。

輸入應為多維陣列或物件陣列。

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

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

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

範例

$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

傳回一個值,指示給定的陣列是否為關聯陣列。

如果陣列的所有鍵都是字串,則該陣列是關聯陣列。如果 $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)

檢查陣列或 Traversable 是否包含元素。

此方法的作用與 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

傳回一個值,指示給定的陣列是否為索引陣列。

如果陣列的所有鍵都是整數,則該陣列是索引陣列。如果 $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)

檢查陣列或 Traversable 是否為另一個陣列或 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)

檢查變數是否為陣列或 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

檢查給定的陣列是否包含指定的鍵。

此方法透過支援不區分大小寫的鍵比較來增強 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

從多維陣列或物件陣列建立映射(鍵值對)。

$from$to 參數指定要設定映射的鍵名或屬性名稱。或者,可以根據分組欄位 $group 進一步分組映射。

範例,

$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

將兩個或多個陣列遞迴合併為一個。

如果每個陣列都有一個具有相同字串鍵值的元素,則後者將覆寫前者(與 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

依據一個或多個鍵對物件陣列或陣列(具有相同結構)進行排序。

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

遞迴排序陣列。

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

從陣列中移除一個項目並傳回該值。如果鍵在陣列中不存在,則會傳回預設值。

用法範例,

// $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)

從陣列中移除具有匹配值的項目,並傳回已移除的項目。

範例,

$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)

將值寫入指定鍵路徑的關聯陣列中。

如果還沒有這樣的鍵路徑,它將被遞迴建立。如果鍵存在,它將被覆寫。

 $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

將物件或物件陣列轉換為陣列。

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