为什么我的代码array_search不起作用?我在没有$ _POST的情况下使用它并且一切正常。但现在我无法理解。
<_php
$arr = array(
'Tokyo' => 'Japan',
'Mexico City' => 'Mexico',
'New York City' => 'USA',
'Mumbai' => 'India',
'Seoul' => 'Korea',
'Shanghai' => 'China',
'Lagos' => 'Nigeria',
'Buenos Aires' => 'Argentina',
'Cairo' => 'Egypt',
'London' => 'England');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post" action="exercise.php">
<select name="city">
<?php
foreach ($arr as $a => $b)
{
echo "<option>$a</option>";
}
?>
</select>
<input type="submit" value="get a city">
</form>
<?php
if ($_POST)
{
$city=$_POST['city'];
$country=array_search($city, $arr);
echo "<p>$city is in $country.</p>" ;
}
?>
</body>
</html>
我已经检查了$ country的类型及其字符串,我也试过使用$ _POST [&#39; city&#39;]代替$ country但它仍然没有&#39工作。 我做错了什么?
答案 0 :(得分:1)
array_search()在这里不起作用,因为array_search正在搜索数组的值,而不是键。
正如你所知,正如亚历克斯建议的那样,最好的选择是。但是你也应该先使用array_key_exists()检查密钥是否存在,因为你无法保证$ _POST中的值将是你期望的值之一,否则会导致E_NOTICE被抛出。
$country = (array_key_exists($city, $arr)) ? $arr[$city] : null;
答案 1 :(得分:0)
您不需要array_search()
,只需直接使用索引值:
$city = $_POST['city'];
$country = $arr[$city];
echo "<p>$city is in $country.</p>" ;