在 PHP 中,array_change_key_case() 函数可以轻松将数组中的所有键名转换为小写或大写。但有时我们并不想转换整个数组的所有键,而是只想转换其中的。这时候,就需要一点技巧来实现这个目标。
本文将介绍一种方法,让你能够“精准地”对数组中指定的键使用 array_change_key_case() 的功能。
假设我们有如下数组:
$data = [
'Name' => 'Alice',
'AGE' => 25,
'Gender' => 'Female',
'Country' => 'Canada'
];
我们只想将 Name 和 Country 的键名转换为小写,其余保持不变。标准的 array_change_key_case($data, CASE_LOWER) 会改变所有的键,这显然不符合我们的需求。
我们可以遍历数组,判断当前键是否在我们指定的列表中,如果是,就进行大小写转换,然后重新构建数组。
function change_selected_keys_case(array $array, array $keysToChange, int $case = CASE_LOWER): array {
$result = [];
foreach ($array as $key => $value) {
if (in_array($key, $keysToChange)) {
$newKey = ($case === CASE_UPPER) ? strtoupper($key) : strtolower($key);
} else {
$newKey = $key;
}
$result[$newKey] = $value;
}
return $result;
}
$data = [
'Name' => 'Alice',
'AGE' => 25,
'Gender' => 'Female',
'Country' => 'Canada'
];
$keysToChange = ['Name', 'Country'];
$modified = change_selected_keys_case($data, $keysToChange, CASE_LOWER);
print_r($modified);
Array
(
[name] => Alice
[AGE] => 25
[Gender] => Female
[country] => Canada
)
如你所见,只有 Name 和 Country 被转为了小写,其他的键没有发生变化。
如果你需要处理嵌套数组,或是键名的匹配需要不区分大小写,可以对函数做进一步优化,比如使用 strtolower() 对比键名等。
也可以将函数改造成更通用的版本,比如支持回调函数来决定是否转换某个键:
function change_keys_with_callback(array $array, callable $shouldChange, int $case = CASE_LOWER): array {
$result = [];
foreach ($array as $key => $value) {
$newKey = $shouldChange($key) ?
(($case === CASE_UPPER) ? strtoupper($key) : strtolower($key)) :
$key;
$result[$newKey] = $value;
}
return $result;
}
用法示例:
$modified = change_keys_with_callback($data, function($key) {
return in_array($key, ['Name', 'Country']);
});
虽然 PHP 没有原生支持只对指定键使用 array_change_key_case() 的功能,但通过简单的遍历和判断逻辑,我们完全可以实现相同的效果。这种方式不仅灵活,还能让你控制转换逻辑,非常适合实际开发场景。