array_keys
是 PHP 中的一个内置函数,用于返回数组中所有键名的数组。这个函数可以帮助你更轻松地处理和操作数组。以下是一些使用 array_keys
的技巧和示例:
$array = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
$keys = array_keys($array);
print_r($keys); // 输出: Array ( [0] => name [1] => age [2] => city )
$array = array(
"apple" => 1,
"banana" => 2,
"orange" => 3
);
$key = array_search(2, $array);
echo $key; // 输出: banana
$array = array(
"c" => "C",
"a" => "A",
"b" => "B"
);
ksort($array);
print_r($array); // 输出: Array ( [a] => A [b] => B [c] => C )
$array = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
$keyToDelete = "age";
unset($array[$keyToDelete]);
print_r($array); // 输出: Array ( [name] => John [city] => New York )
$array = array(
"Name" => "John",
"Age" => 30,
"City" => "New York"
);
$keys = array_keys($array);
$lowercaseKeys = array_map("strtolower", $keys);
$newArray = array_combine($lowercaseKeys, $array);
print_r($newArray); // 输出: Array ( [name] => John [age] => 30 [city] => New York )
$array = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
$flippedArray = array_flip($array);
print_r($flippedArray); // 输出: Array ( [John] => name [30] => age [New York] => city )
这些技巧和示例展示了如何使用 array_keys
和其他数组操作函数来处理和操作 PHP 数组。你可以根据实际需求调整这些示例以满足你的需求。