array_change_key_case
(PHP 4 >= 4.2.0, PHP 5)
array_change_key_case — Возвращает массив, символьные ключи которого преобразованы в верхний или нижний регистр символов
Описание
Функция array_change_key_case() преобразует ключи массива input в верхний или нижний регистр символов. Тип преобразования зависит от последнего опционального параметра case . В качестве этого параметра вы можете передать одну из двух констант: CASE_UPPER и CASE_LOWER. По умолчанию используется CASE_LOWER. Эта функция не изменяет ключи, состоящие из чисел.
Пример #1 Пример использования array_change_key_case()
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
Результатом выполнения вышеприведенной программы будет:
Array ( [FIRST] => 1 [SECOND] => 2 )
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения, относящиеся к переменным и типам
- Массивы
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_key_exists
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- each
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
Коментарии
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
)
*/
<?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;
}
?>
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;
}
?>
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;
}
?>
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
)
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 )
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));
}
<?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)
);
}
?>
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));
}
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
)
)
Array of partitions with always the same number of sub-array indexes.
<?php
function partitionFixedSubArray($array, $length, $empty_space)
{
$result = [];
if ( sizeof($array) ) {
$result = array_chunk($array, $length);
$last_array_count = sizeof(end($result));
if ($last_array_count < $length) {
for ($i = $last_array_count; $i < $length; $i++) {
array_push($result[key($result)], $empty_space);
}
}
}
return $result;
}
$employees = [
"Paidi",
"Paijo",
"Darno",
"Kusnan",
"Mukidi",
"Sarno",
"Nurdin",
"Parmen",
"Sukinah",
"Sartini",
"Sukijan",
"Yono",
"Supoyo"
];
echo "<pre>";
print_r(partitionFixedSubArray($employees, 5, "empty space"));
echo "</pre>";
?>
Output:
Array
(
[0] => Array
(
[0] => Paidi
[1] => Paijo
[2] => Darno
[3] => Kusnan
[4] => Mukidi
)
[1] => Array
(
[0] => Sarno
[1] => Nurdin
[2] => Parmen
[3] => Sukinah
[4] => Sartini
)
[2] => Array
(
[0] => Sukijan
[1] => Yono
[2] => Supoyo
[3] => empty space
[4] => empty space
)
)
//Array key case change recursively (Unicode):
<?php
function array_key_case($data,$case=FALSE)
{
$ret=array();
if ( is_array($data) )
foreach ($data as $idx => $val)
$ret[$case ? mb_strtoupper($idx) : mb_strtolower($idx)]=array_key_case($val,$case);
else
$ret=$data;
return $ret;
}