In daily development, we often obtain JSON data from third-party interfaces. However, the case format of key names in the data returned by these interfaces is inconsistent, some start with capital, and some are all capital or all lower case. This inconsistent key name format will cause a lot of trouble in the subsequent processing of data, such as field extraction, unified mapping, array conversion to objects, etc., which may make errors or become lengthy.
Fortunately, PHP provides a very practical function: array_change_key_case() , which helps us to elegantly and efficiently unify key names in arrays , thus solving this problem.
array_change_key_case() is a built-in function in PHP, which is used to convert the upper and lowercase or uppercase cases of all key names in the array.
array_change_key_case(array $array, int $case = CASE_LOWER): array
$array : the associative array to be processed;
$case : converts the target case type, CASE_LOWER (default) means convert to lowercase, and CASE_UPPER means convert to uppercase.
Let's use a real JSON string as an example to demonstrate how to elegantly unify key names with upper and lower case.
{
"UserID": 101,
"UserName": "Alice",
"Email": "alice@example.com"
}
As you can see, the key names are case-mixed. When processing, for convenience, we want to convert all to lowercase key names.
<?php
// Assume this is from the interface https://api.m66.net/user Data obtained
$json = '{
"UserID": 101,
"UserName": "Alice",
"Email": "alice@example.com"
}';
// first step:Will JSON Convert to associative array
$data = json_decode($json, true);
// Step 2:use array_change_key_case() Will键名统一转为小写
$normalized = array_change_key_case($data, CASE_LOWER);
// Output processed array
print_r($normalized);
/*
Output result:
Array
(
[userid] => 101
[username] => Alice
[email] => alice@example.com
)
*/
?>
In this way, we can use $normalized['username'] and other methods to obtain values without worrying about the problem of inconsistent case of key names.
If JSON is a multi-layer nested structure, using array_change_key_case() alone can only process the first layer, and we need to encapsulate a recursive function to handle all levels:
function array_keys_to_lower_recursive(array $array): array {
$result = [];
foreach ($array as $key => $value) {
$key = is_string($key) ? strtolower($key) : $key;
$result[$key] = is_array($value) ? array_keys_to_lower_recursive($value) : $value;
}
return $result;
}
The usage method is similar to the above:
$normalized = array_keys_to_lower_recursive($data);
When you process JSON data and want to unify key case, array_change_key_case() is a simple and efficient tool. With the recursive version, it can also handle more complex data structures. This not only improves the readability of the code, but also reduces maintenance costs.