array_keys
是 PHP 中的一個內置函數,它用于返回數組中所有鍵名的數組。以下是 array_keys
在 PHP 中的一些實際應用案例:
$assoc_array = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
$keys = array_keys($assoc_array);
print_r($keys); // 輸出: Array ( [0] => name [1] => age [2] => city )
$numbers = array(
1 => 10,
2 => 20,
3 => 30,
4 => 40,
5 => 50
);
$even_keys = array_filter(array_keys($numbers), function ($key) use ($numbers) {
return $numbers[$key] % 2 == 0;
});
print_r($even_keys); // 輸出: Array ( [1] => 2 [3] => 4 )
$fruits = array(
"apple" => 5,
"orange" => 8,
"banana" => 3,
"grape" => 10
);
// 按值排序
asort($fruits);
// 獲取排序后的鍵名
$sorted_keys = array_keys($fruits);
print_r($sorted_keys); // 輸出: Array ( [2] => banana [0] => apple [1] => orange [3] => grape )
$colors = array(
"red" => "#FF0000",
"green" => "#00FF00",
"blue" => "#0000FF",
"yellow" => "#FFFF00"
);
$key_to_delete = "green";
if (($key_index = array_search($key_to_delete, array_keys($colors))) !== false) {
unset($colors[$key_to_delete]);
}
print_r($colors); // 輸出: Array ( [red] => #FF0000 [blue] => #0000FF [yellow] => #FFFF00 )
這些示例展示了如何在 PHP 中使用 array_keys
函數處理關聯數組。根據實際需求,可以調整代碼來滿足不同場景下的操作。