略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: array_change_key_case

2024-11-13

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

array_change_key_case将数组中的所有键名修改为全大写或小写

说明

array_change_key_case(array $array, int $case = CASE_LOWER): array

array_change_key_case()array 数组中的所有键名改为全小写或大写。本函数不改变数字索引。

参数

array

需要操作的数组。

case

可以在这里用两个常量,CASE_UPPERCASE_LOWER(默认值)。

返回值

返回一个键全是小写或者全是大写的数组;如果输入值(array)不是一个数组,则返回 null

错误/异常

如果输入值(array)不是一个数组,就会抛出一个错误警告(E_WARNING)。

范例

示例 #1 array_change_key_case()例一

<?php
$input_array 
= array("FirSt" => 1"SecOnd" => 4);
print_r(array_change_key_case($input_arrayCASE_UPPER));
?>

以上例程会输出:

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

注释

注意:

如果一个数组中的多个键名经过本函数后变成一样的话(例如 "keY" 和 "kEY"),最后一个值将覆盖其它的值。

add a noteadd a note

User Contributed Notes 18 notes

up
27
qeremy [atta] gmail [dotta] com
10 years ago
Unicode example;

<?php
function array_change_key_case_unicode($arr, $c = CASE_LOWER) {
   
$c = ($c == CASE_LOWER) ? MB_CASE_LOWER : MB_CASE_UPPER;
    foreach (
$arr as $k => $v) {
       
$ret[mb_convert_case($k, $c, "UTF-8")] = $v;
    }
    return
$ret;
}

$arr = array("FirSt" => 1, "yağ" => "Oil", "şekER" => "sugar");
print_r(array_change_key_case($arr, CASE_UPPER));
print_r(array_change_key_case_unicode($arr, CASE_UPPER));
?>

Array
(
    [FIRST] => 1
    [YAğ] => Oil
    [şEKER] => sugar
)
Array
(
    [FIRST] => 1
    [YAĞ] => Oil
    [ŞEKER] => sugar
)
up
3
msegit post pl
1 year ago
Improved multidimensional unicode func (after qeremy):
<?php
function array_change_key_case_unicode_recurs($arr, $c = CASE_LOWER) {
    foreach (
$arr as $k => $v) {
       
$ret[mb_convert_case($k, (($c === CASE_LOWER) ? MB_CASE_LOWER : MB_CASE_UPPER), "UTF-8")] = (is_array($v) ? array_change_key_case_unicode_recurs($v, $c) : $v );
    }
    return
$ret;
}

$arr = array("FirSt" => 1, "ZażóŁć gęŚlą jaŹń" => array("yağ" => "Oil", "şekER" => "sugar") );
print_r(array_change_key_case($arr, CASE_UPPER));
print_r(array_change_key_case_unicode_recurs($arr, CASE_UPPER));
?>

Array
(
    [FIRST] => 1
    [ZAżóŁć GęŚLą JAŹń] => Array
        (
            [yağ] => Oil
            [şekER] => sugar
        )
)
Array
(
    [FIRST] => 1
    [ZAŻÓŁĆ GĘŚLĄ JAŹŃ] => Array
        (
            [YAĞ] => Oil
            [ŞEKER] => sugar
        )
)
up
5
zhangxuejiang
2 years ago
I improve the array_change_key_case_recursive function ,let it can lowercase or uppercase keys

function array_change_key_case_recursive($arr, $case = CASE_LOWER)
{
    return array_map(function($item) use($case) {
        if(is_array($item))
            $item = array_change_key_case_recursive($item, $case);
        return $item;
    },array_change_key_case($arr, $case));
}
up
12
xsaero00
8 years ago
Here is the most compact way to lower case keys in a multidimensional array

function array_change_key_case_recursive($arr)
{
    return array_map(function($item){
        if(is_array($item))
            $item = array_change_key_case_recursive($item);
        return $item;
    },array_change_key_case($arr));
}
up
1
shaman_master at list dot ru
2 years ago
<?php
/**
* Convert keys in an array.
*
* @param array $array Source data
* @param callable $callback Function name (strtolower, strtoupper, ucfirst, lcfirst, ucwords)
* @return array
*/
function array_convert_key_case(array $array, callable $callback = 'strtolower')
{
    return
array_combine(
       
array_map($callback, array_keys($array)),
       
array_values($array)
    );
}
?>
up
-2
andreas dot schuhmacher87 at googlemail dot com
14 years ago
multibyte and multi-dimensional-array support, have fun!

<?php
    define
('ARRAY_KEY_FC_LOWERCASE', 25); //FOO => fOO
   
define('ARRAY_KEY_FC_UPPERCASE', 20); //foo => Foo
   
define('ARRAY_KEY_UPPERCASE', 15); //foo => FOO
   
define('ARRAY_KEY_LOWERCASE', 10); //FOO => foo
   
define('ARRAY_KEY_USE_MULTIBYTE', true); //use mutlibyte functions
   
    /**
    * change the case of array-keys
    *
    * use: array_change_key_case_ext(array('foo' => 1, 'bar' => 2), ARRAY_KEY_UPPERCASE);
    * result: array('FOO' => 1, 'BAR' => 2)
    *
    * @param    array
    * @param    int
    * @return     array
    */
   
function array_change_key_case_ext(array $array, $case = 10, $useMB = false, $mbEnc = 'UTF-8') {
       
$newArray = array();
       
       
//for more speed define the runtime created functions in the global namespace
       
        //get function
       
if($useMB === false) {
           
$function = 'strToUpper'; //default
           
switch($case) {
               
//first-char-to-lowercase
               
case 25:
                   
//maybee lcfirst is not callable
                   
if(!function_exists('lcfirst'))
                       
$function = create_function('$input', '
                            return strToLower($input[0]) . substr($input, 1, (strLen($input) - 1));
                        '
);
                    else
$function = 'lcfirst';
                    break;
               
               
//first-char-to-uppercase               
               
case 20:
                   
$function = 'ucfirst';
                    break;
               
               
//lowercase
               
case 10:
                   
$function = 'strToLower';
            }
        } else {
           
//create functions for multibyte support
           
switch($case) {
               
//first-char-to-lowercase
               
case 25:
                   
$function = create_function('$input', '
                        return mb_strToLower(mb_substr($input, 0, 1, \''
. $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \''
. $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    '
);
                   
                    break;
               
               
//first-char-to-uppercase
               
case 20:
                   
$function = create_function('$input', '
                        return mb_strToUpper(mb_substr($input, 0, 1, \''
. $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \''
. $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    '
);
                   
                    break;
               
               
//uppercase
               
case 15:
                   
$function = create_function('$input', '
                        return mb_strToUpper($input, \''
. $mbEnc . '\');
                    '
);
                    break;
               
               
//lowercase
               
default: //case 10:
                   
$function = create_function('$input', '
                        return mb_strToLower($input, \''
. $mbEnc . '\');
                    '
);
            }
        }
       
       
//loop array
       
foreach($array as $key => $value) {
            if(
is_array($value)) //$value is an array, handle keys too
               
$newArray[$function($key)] = array_change_key_case_ex($value, $case, $useMB);
            elseif(
is_string($key))
               
$newArray[$function($key)] = $value;
            else
$newArray[$key] = $value; //$key is not a string
       
} //end loop
       
       
return $newArray;
    }
?>
up
-3
JOE
10 years ago
Script to change case of sub-arrays keys to lower . It works well for me. hope it helps.

<?php
$array
=array("First"=>"val1","SecoNd"=>"val2",
"third"=>array("third-INner1"=>"val3.1"),
"fourth"=>array("FouthINNer1"=>"val4.1","FourthINNER2"=>"val4.2"));
print_r($array);
$key=array_keys($array);
foreach(
$key as $ki)
{
   
$klower=strtolower($ki);
   
$val=$array[$ki];
    if(
is_array($val))
    {
        foreach(
$val as $kinner=>$vinner)
        {
           
           
$tl=strtolower($kinner);
            unset(
$val[$kinner]);
           
$val[$tl]=$vinner;
        }
    }
    unset(
$array[$ki]);
   
$array[$klower]=$val;
}
echo
"<br> After Changing Key to-LowerCase : <br>";
print_r($array);

?>
up
-3
anon at ymous dot com
13 years ago
Below is a recursive version of this function.

<?php
   
/**
     * A recursive array_change_key_case function.
     * @param array $input
     * @param integer $case
     */
   
function array_change_key_case_recursive($input, $case = null){
        if(!
is_array($input)){
           
trigger_error("Invalid input array '{$array}'",E_USER_NOTICE); exit;
        }
       
// CASE_UPPER|CASE_LOWER
       
if(null === $case){
           
$case = CASE_LOWER;
        }
        if(!
in_array($case, array(CASE_UPPER, CASE_LOWER))){
           
trigger_error("Case parameter '{$case}' is invalid.", E_USER_NOTICE); exit;
        }
       
$input = array_change_key_case($input, $case);
        foreach(
$input as $key=>$array){
            if(
is_array($array)){
               
$input[$key] = array_change_key_case_recursive($array, $case);
            }
        }
        return
$input;
    }
?>
up
-3
oulala at yandex dot com
6 years ago
Recursive LowerCase First Letter in array key

if(!function_exists("mb_lcfirstKeys")) {
    function mb_lcfirstKeys($data) {
        $res = [];
        foreach ($data as $key => $value) {
            $newKey = mb_lcfirst($key);
            $res[$newKey] = is_array($value) ? mb_lcfirstKeys($value) : $value;
        }
        return $res;
    }
}
up
-3
cm at gameswelt dot de
14 years ago
I just changed the code a little bit so you havent got a code that repeats itself.

<?php

function array_change_key_case_secure($array = array(), $case = CASE_UPPER){
   
$secure = array();
   
$functionWrap = array(CASE_UPPER => 'strtoupper',
                           
CASE_LOWER => 'strtolower');
                           
    foreach(
$array as $key => $val){
        if(isset(
$functionWrap[$key])){
           
$key = $functionWrap[$case]($key);
           
$secure[$key][] = $val;
        } else {
            die(
'Not a known Type');
        }
    }
   
    foreach(
$secure as $key => $val){
        if(
count($secure[$key]) == 1){
           
$secure[$key] = $val[0];
        }
    }
   
    return
$secure;
}

$myArray = array('A' => 'Hello',
                   
'B' => 'World',
                   
'a' => 'how are you?');

print_r($myArray);
$myArray = array_change_key_case_secure($myArray);
print_r($myArray);

/*
Array
(
    [A] => Hello
    [B] => World
    [a] => how are you?
)
Array
(
    [A] => Array
        (
            [0] => Hello
            [1] => how are you?
        )

    [B] => World
)
*/
up
-6
Lus Henrique Pessoa
11 years ago
<?php

// improving the previous script
function ack_r3(&$array, $case=CASE_LOWER, $flag_rec=false)
    {
     
$array = array_change_key_case($array, $case);
      if (
$flag_rec ) {
        foreach (
$array as $key => $value) {
            if (
is_array($value) ) {
               
ack_r3($array[$key], $case, true);
            }
        }
      }
    }

// same of array_change_key_case
$arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
   
ack_r3($arr, CASE_LOWER,false);
   
var_dump($arr);
   
   
$arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
   
ack_r3($arr, CASE_LOWER,true);
   
var_dump($arr);

?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["PHONE"]=>
    string(9) "3010-7148"
    ["E-MAIL"]=>
    string(12) "luis@net.com"
  }
}
array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
up
-5
john at doe dot com
14 years ago
<?php
function array_change_value_case($input, $case = CASE_LOWER)
{
   
$aRet = array();
   
    if (!
is_array($input))
    {
        return
$aRet;
    }
   
    foreach (
$input as $key => $value)
    {
        if (
is_array($value))
        {
           
$aRet[$key] = array_change_value_case($value, $case);
            continue;
        }
       
       
$aRet[$key] = ($case == CASE_UPPER ? strtoupper($value) : strtolower($value));
    }
   
    return
$aRet;
}
?>
up
-5
NetPanther
9 years ago
Use this to capitalize first letter of all array keys:

<?php

function ucfirstKeys(&$data)
{
  foreach (
$data as $key => $value)
  {
   
// Convert key
   
$newKey = ucfirst($key);

   
// Change key if needed
   
if ($newKey != $key)
    {
      unset(
$data[$key]);
     
$data[$newKey] = $value;
    }

   
// Handle nested arrays
   
if (is_array($value))
    {
     
ucfirstKeys($data[$key]);
    }
  }
}

$test = array('foo' => 'bar', 'moreFoo' => array('more' => 'foo'));
ucfirstKeys($test);
print_r($test);

?>

Result:
Array ( [MoreFoo] => Array ( [More] => foo ) [Foo] => bar )
up
-5
ahmadz
5 years ago
function convert_to_key_case($data, $case){

        $condition = ($case == 'lowercase')? 'lowercase' : 'uppercase';
        $test = [];
        foreach($data as  $key => $value) {
            if ($condition == 'lowercase') {
                $test[strtolower($key)] = $value;
            } else {
                $test[strtoupper($key)] = $value;
            }
        }
    return $test;
}

$input = ['test1'=>1, 'Test2' => 2, 'TeSt3' => 3];

print_r(convert_to_key_case($input, 'uppercase'));
print_r(convert_to_key_case($input, 'lowercase'));

OUTPUT

Array
(
[TEST1] => 1
[TEST2] => 2
[TEST3] => 3
)

Array (
[test1] => 1
[test2] => 2
[test3] => 3
)
up
-7
Luis Henrique Pessoa
11 years ago
Script to change case of sub-arrays keys:

<?php

   
function arrKey2Lower(&$arrVals) {
        foreach(
$arrVals as $key => $item ) {
           
$key2 = strtolower($key);
            if (
$key2 != $key) {
                unset(
$arrVals[$key]);
               
$arrVals[$key2]=$item;
               
$key=$key2;
            }
           
            if (
is_array($item) ) { arrKey2Lower($arrValores[$key]); }
        }
    }
   
   
$arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
   
arrKey2Lower($arr);
   
var_dump($arr);
   
   
?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
up
-9
info at microweb dot lt
12 years ago
Simple function to change multidimensional array's all values to uppercase. If you would like to change to lowercase then change "mb_strtoupper" to  "mb_strtolower". It works perfect for me ;)

<?php
function change_case_recursive($arr){
    foreach (
$arr as $key=>$val){
        if (!
is_array($arr[$key])){
           
$arr[$key]=mb_strtoupper($arr[$key]);
        }else{
           
$arr[$key]=change_case_recursive($arr[$key]);
        }
    }
    return
$arr;   
}
?>
up
-13
david at ramaboo dot com
13 years ago
Same as array_change_key_case only with the values. This should really be part of PHP!

<?php
/**
* @brief Returns an array with all values lowercased or uppercased.
* @return array Returns an array with all values lowercased or uppercased.
* @param object $input The array to work on
* @param int $case [optional] Either \c CASE_UPPER or \c CASE_LOWER (default).
*/
function array_change_value_case(array $input, $case = CASE_LOWER) {
    switch (
$case) {
        case
CASE_LOWER:
            return
array_map('strtolower', $input);
            break;
        case
CASE_UPPER:
            return
array_map('strtoupper', $input);
            break;
        default:
           
trigger_error('Case is not valid, CASE_LOWER or CASE_UPPER only', E_USER_ERROR);
            return
false;
    }
}
?>
up
-20
charles
13 years ago
<?php
$input_array
= array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>

官方地址:https://www.php.net/manual/en/function.array-change-key-case.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3