2

I'm accessing an API which is returning the value of an array. I want a image to be displayed based on the result. For example if the div contains "above average" then display an image called aboveAverage.png.

echo $cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'];

This results is "Above Average" How can I display a particular image to correspond to this?

Something like ->

if Div "crime_level" = above average then:
display aboveAverage.png

I'm pretty new to PHP, sorry i'm a noob.

4

5 回答 5

3

使用案例选择开关

switch ($cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level']) {  
            case "Above Average":
                $image = "aboveAverage.png";
            break;
            case "Below Average":
                $image = "belowAverage.png";
            break;
            default:
                $image = "unknown.png";
            };

echo "<img src=\"$image\" />";

这样做可以让您通过将变量设置为 $image 来从显示中删除逻辑,这样您就不必更新 20 个不同的潜在图像标签。它还允许您满足字符串的许多不同情况,而不会最终迷失在 if then else 地狱中

于 2013-05-09T14:52:45.417 回答
3

如果值

$cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level']

是有限的,并且您碰巧知道它们,您可以使用关联数组,其中键是 API 返回的值,而与该键对应的值是您要显示的图像的文件名。就像是:

$images = array(
    'Above Average' => 'aboveAverage.png',
    'Below Average' => 'belowAverage.png',
    // etc
);

$img = 'default.png'; // set a default image file

$crimeRate = $cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'];
if (array_key_exists($crimeRate, $images)) {
    $img = $images[$crimeRate];
}

// output the image
echo "<img src=" . $img . " />";
于 2013-05-09T14:56:00.940 回答
1

你的问题有两个部分。首先是如何将数组元素与字符串进行比较。这是这样完成的:

if ( $cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'] == "Above average" ) {
    // The second part of your question is how to display an image.
    echo '<img src="aboveAverage.php" />;
}

还有其他方法可以通过 PHP 脚本显示图像,例如设置适当的标题和直接转储图像内容。如果您正在寻找这样的解决方案,请参阅在 PHP 中输​​出图像

于 2013-05-09T14:53:09.233 回答
0

这是一些方法:

$toDisplay = array("Above average", "Average") ;

if (in_array($cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'], $toDisplay)){
  echo "<img src='image.png' alt='image'/>" ;
}
于 2013-05-09T14:51:46.057 回答
0

一个简单的 if 和 echo 就可以了:

if ($cinfo['crimes']['2013-03']['anti-social-behaviour']['crime_level'] == "above average") {
    echo "<img src='aboveAverage.png' />
}
于 2013-05-09T14:51:54.783 回答