2014-12-18 34 views
0

我编写了一个脚本,用于根据用户所在的城市动态更改<div>的背景。用户城市显示在变量$city = 'New York';中。使用PHP Array制作动态背景图片

我在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>'; 
      } 

我在做什么错了?

回答

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; 
+0

感谢您的快速响应。如果未设置,我该如何设置它... – Rizzo

+0

使用'isset()'将检查它是否存在,然后您可以使用:'$ cities [$ city] ['bg']'检索值 –

4

in_array函数返回一个布尔值,所以你不需要比较检查。只需使用以下条件:

if (in_array($city, $cities)) { ... } 
+0

谢谢,我都试过'array_search()'和'in_array'我在与显示图像,如果if语句比较的问题它存在.. – Rizzo