我编写了一个脚本,我希望根据用户所在的城市动态更改<div>
的背景。用户城市显示在变量$city = 'New York';
。
我在PHP中有一个数组来处理城市和相关的图像:
$cities = array(
"Boston" => array(
'name' => 'Boston',
'bg' => 'bs.png'
),
"New York" => array(
'name' => 'New York',
'bg' => 'ny.png'
),
"Denver" => array(
'name' => 'Denver',
'states' => 'CO', 'WY', 'NE'
),
);
我在编写if语句时遇到问题,该语句会识别城市并将其拉入<style>
标记。这就是我写的,但它根本不起作用:
if ($city === in_array($city, $cities)) {
echo '<style>
.header {
background: url(img/'.$cities['bg'].') no-repeat center center scroll;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}
</style>';
} else {
echo '<style>
.header {
background: url(img/bg.jpg) no-repeat center center scroll;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}
</style>';
}
我做错了什么?
答案 0 :(得分:4)
in_array
函数返回一个布尔值,因此您不需要进行比较检查。只需使用以下条件:
if (in_array($city, $cities)) { ... }
答案 1 :(得分:2)
$cities['bg']
将始终未定义。您需要确保它已设置。您可以使用isset()
只需要进行一次条件检查:
<?php
$cities = array(
"Boston" => array(
'name' => 'Boston',
'bg' => 'bs.png'
),
"New York" => array(
'name' => 'New York',
'bg' => 'ny.png'
),
"Denver" => array(
'name' => 'Denver',
'states' => 'CO', 'WY', 'NE'
),
);
$city = 'New York';
$bg = 'bg.jpg';
if ( isset($cities[$city]['bg']) ){
$bg = $cities[$city]['bg'];
}
echo <<<EOD
<style>
.header {
background: url(img/{$bg}) no-repeat center center scroll;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}
</style>
EOD;