小写所有没有 foreach 的关联数组键

Lowercase all the associative array keys without foreach

我有一个由这个变量保存的数组:

$get_multiple_role_will_redirect = isset($_POST['multiple_role_will_redirect']) ? $_POST['multiple_role_will_redirect'] : 0;

Array
(
    [Administrator] => 
    [Editor] => 
    [Author] => 
    [Contributor] => 
    [Subscriber] => 
    [Shop_manager] => 
    [Shop_accountant] => 
    [Shop_worker] => 
    [Shop_vendor] => 
    [Edd_subscriber] => 
    [Customer] => 
)

现在,我想将所有键都小写。为此,我正在这样做 foreach:

$multiple_role_will_redirect = [];
foreach($get_multiple_role_will_redirect as $key => $value) {
    $key = strtolower($key);
    $multiple_role_will_redirect[$key] = $value;
}

我的问题是,如果没有 foreach 循环到 lowercase 数组 key,还有其他方法吗?

我已经检查过:

array_filter($get_multiple_role_will_redirect, 'strtolower');

但它不是小写的数组键。

我认为 array_change_key_case 功能适合你。

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
print_r(array_change_key_case($age,CASE_LOWER));

https://www.w3schools.com/php/func_array_change_key_case.asp

我只是想证明没有循环是不可能的。对于已接受的答案,array_change_key_case 也具有 ZEND_HASH_FOREACH_KEY_VAL

的循环实现

参考array_change_key_case的源码src: array_change_key_case

PHP_FUNCTION(array_change_key_case)
{
    zval *array, *entry;
    zend_string *string_key;
    zend_string *new_key;
    zend_ulong num_key;
    zend_long change_to_upper=0;

    ZEND_PARSE_PARAMETERS_START(1, 2)
        Z_PARAM_ARRAY(array)
        Z_PARAM_OPTIONAL
        Z_PARAM_LONG(change_to_upper)
    ZEND_PARSE_PARAMETERS_END();

    array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array)));

    ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(array), num_key, string_key, entry) {
        if (!string_key) {
            entry = zend_hash_index_update(Z_ARRVAL_P(return_value), num_key, entry);
        } else {
            if (change_to_upper) {
                new_key = php_string_toupper(string_key);
            } else {
                new_key = php_string_tolower(string_key);
            }
            entry = zend_hash_update(Z_ARRVAL_P(return_value), new_key, entry);
            zend_string_release_ex(new_key, 0);
        }

        zval_add_ref(entry);
    } ZEND_HASH_FOREACH_END();
}

您可以通过将旧数组中的小写键与旧数组中的值组合来创建一个新数组。这里替换原来的。

<?php

$items = 
[
    'Foo' => 'hello',
    'Bar' => 'world'
];

$items = array_combine(
    array_map('strtolower', array_keys($items)), 
    $items
);

var_export($items);

输出:

array (
    'foo' => 'hello',
    'bar' => 'world',
  )