array_change_key_case

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

把数组全部键统一转小写或大写(CASE_LOWER/CASE_UPPER);HTTP 头、配置键归一化的专用工具。

C C23

C23
#include <ctype.h>
#include <stdio.h>
#include <string.h>

/* C 字符串就是数组:键转小写就是逐字符写入 */
static void lower_key(char *k) {
    for (int i = 0; k[i]; i++) k[i] = (char)tolower((unsigned char)k[i]);
}

int main(void) {
    char key[] = "Content-Type";
    lower_key(key);
    printf("%s\n", key); /* content-type */
    return 0;
}
输出
content-type

C++ C++26

C++26
#include <algorithm>
#include <cctype>
#include <iostream>
#include <map>
#include <string>

static std::string lowered(std::string k) {
    std::transform(k.begin(), k.end(), k.begin(),
                   [](unsigned char c) { return std::tolower(c); });
    return k;
}

int main() {
    std::map<std::string, std::string> m = {
        { "Content-Type", "text/html" },
        { "X_REQUEST_ID", "a1" }
    };
    // 用归一键重建
    std::map<std::string, std::string> out;
    for (const auto& [k, v] : m) out[lowered(k)] = v;
    std::cout << out.at("content-type") << "\n";
    std::cout << out.at("x_request_id") << "\n";
    return 0;
}
输出
text/html
a1

C# v11.0.100

v11.0.100
using System.Collections.Generic;
using System.Linq;

class MainClass {
    static void Main() {
        var headers = new Dictionary<string, string> {
            ["Content-Type"] = "text/html",
            ["X_REQUEST_ID"] = "a1"
        };
        // ToDictionary 以归一键重建;Invariant 保证不随区域变化
        var lower = headers.ToDictionary(
            kv => kv.Key.ToLowerInvariant(), kv => kv.Value);
        System.Console.WriteLine(lower["content-type"]);
        System.Console.WriteLine(lower["x_request_id"]);
    }
}
输出
text/html
a1

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"strings"
)

func main() {
	headers := map[string]string{
		"Content-Type": "text/html",
		"X_REQUEST_ID": "a1",
	}
	// 用小写键重建 map;下面的取值不依赖遍历顺序
	lower := make(map[string]string, len(headers))
	for k, v := range headers {
		lower[strings.ToLower(k)] = v
	}
	fmt.Println(lower["content-type"])
	fmt.Println(lower["x_request_id"])
}
输出
text/html
a1

Java v27.0.1

v27.0.1
import java.util.LinkedHashMap;
import java.util.Map;

class Main {
    public static void main(String[] args) {
        Map<String, String> headers = new LinkedHashMap<>();
        headers.put("Content-Type", "text/html");
        headers.put("X_REQUEST_ID", "a1");

        // Locale.ROOT 让 toLowerCase 跨机器结果一致
        Map<String, String> lower = new LinkedHashMap<>();
        headers.forEach((k, v) -> lower.put(k.toLowerCase(java.util.Locale.ROOT), v));
        System.out.println(lower.get("content-type"));
        System.out.println(lower.get("x_request_id"));
    }
}
输出
text/html
a1

JavaScript v26.13.1

v26.13.1
const headers = { "Content-Type": "text/html", X_REQUEST_ID: "a1" };

// fromEntries + map:以归一键重建的惯用形态
const lower = Object.fromEntries(
  Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v])
);
console.log(lower["content-type"]);
console.log(lower["x_request_id"]);
输出
text/html
a1

PHP v8.6.0

v8.6.0
$headers = ["Content-Type" => "text/html", "X_REQUEST_ID" => "a1", "Accept" => "*/*"];

echo json_encode(array_change_key_case($headers, CASE_LOWER)), "\n";
echo json_encode(array_change_key_case($headers, CASE_UPPER)), "\n";
// 默认就是 CASE_LOWER
echo json_encode(array_change_key_case($headers)), "\n";
输出
{"content-type":"text\/html","x_request_id":"a1","accept":"*\/*"}
{"CONTENT-TYPE":"text\/html","X_REQUEST_ID":"a1","ACCEPT":"*\/*"}
{"content-type":"text\/html","x_request_id":"a1","accept":"*\/*"}

Python v3.15.2

v3.15.2
headers = {"Content-Type": "text/html", "X_REQUEST_ID": "a1"}

# 字典推导一遍完成归一键重建
lower = {k.lower(): v for k, v in headers.items()}
print(lower["content-type"])
print(lower["x_request_id"])
输出
text/html
a1

Rust v1.99.1

v1.99.1
use std::collections::HashMap;

fn main() {
    let mut headers = HashMap::new();
    headers.insert("Content-Type", "text/html");
    headers.insert("X_REQUEST_ID", "a1");

    // map + collect 以归一键重建整张表
    let lower: HashMap<String, &str> = headers
        .iter()
        .map(|(k, v)| (k.to_lowercase(), *v))
        .collect();
    println!("{}", lower["content-type"]);
    println!("{}", lower["x_request_id"]);
}
输出
text/html
a1

TypeScript v26.13.1

v26.13.1
const headers: Record<string, string> = {
  "Content-Type": "text/html",
  X_REQUEST_ID: "a1",
};

// 与 JS 运行期同形,按 Record 标注类型
const lower: Record<string, string> = Object.fromEntries(
  Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v])
);
console.log(lower["content-type"]);
console.log(lower["x_request_id"]);
输出
text/html
a1

语言差异说明

C:键是字符串数组(示例原地逐字符 tolower);注意 tolower 收 unsigned char 防 UB;C 里「重建键映射」要手写表结构,示例只演示单键转换。

C++:transform + map 重建(示例);C++ 键归一更稳的做法是用自定义比较器的 std::map(大小写不敏感比较器),查找时不需重建。

C#:ToDictionary(kv => kv.Key.ToLowerInvariant(), ...)(示例);务必用 ToLowerInvariant() 而非 ToLower()——后者随区域设置漂移(土耳其 i 问题);Dictionary 自身构造器可传 StringComparer.OrdinalIgnoreCase,一次配置永久归一。

Go:手写循环 + strings.ToLower(示例);Go 标准库 net/http 的 Header 类型自带 CanonicalMIMEHeaderKey(首字母大写其余小写),HTTP 场景比全小写更常用;注意 map 循环顺序随机,本示例取值不依赖顺序。

Java:forEach + toLowerCase(Locale.ROOT)(示例);必须带 Locale.ROOT——无参 toLowerCase() 随默认区域漂移;TreeMap(String.CASE_INSENSITIVE_ORDER) 是「查找时归一」路线。

JavaScript:Object.fromEntries(entries.map(...)) 是惯用形态(示例);坑:若两个键归一后相同(如 X-Tag 与 x-tag 并存),后写者覆盖先写者且不报错;Headers API(fetch)自带大小写不敏感 get。

PHP:CASE_LOWER 默认、CASE_UPPER 显式(示例);数字键不受影响;冲突合并静默后到优先——["A"=>1,"a"=>2] 归一后剩一个,值取后遍历者;与 HTTP 头场景配套的是 getallheaders()/$_SERVER 键名归一。

Python:字典推导 {k.lower(): v ...}(示例);冲突同样静默覆盖;str.casefold() 比 lower() 更激进(德语 ß→ss),做文本归一时注意。

Rust:iter().map(...).collect()(示例);to_lowercase() 是 Unicode 全小写;冲突键 collect 时后者覆盖前者(HashMap 语义);要查找时归一可用 HashMap<String, V> 键统一在插入侧完成。

TypeScript:同 JS 形态(示例);Record<string, string> 类型层面看不出键归一——归一逻辑是运行期约定,需要文档化。