简体   繁体   English

如何使用foreach将if语句重复放入php数组中?

[英]How do I make a repeated if statement into a php array using foreach?

In PHP, I'm trying to add a different colored block for each different type of music genre. 在PHP中,我试图为每种不同类型的音乐类型添加不同的彩色块。 Each color represents a specific genre. 每种颜色代表特定的流派。 I have 12 genres, but I've only included 3 of those for simplification purposes. 我有12种类型,但是为了简化起见,我只包括了3种类型。

First I get the genre value with 首先,我获得了流派价值

$genre = get_post_meta($post->ID, 'genre', true);

Then I'm using an if statement like so (though it doesn't work past the 2nd genre) 然后,我使用像这样的if语句(尽管它在第二种类型下不起作用)

if($genre == "EDM")
echo '<div style="display:block;width:100%;height:10px;background-color:#9B86FF;"></div>';

else if($genre == "Hip-Hop")
echo '<div style="display:block;width:100%;height:10px;background-color:#56FFCE;"></div>';

else if($genre == "Rock")
echo '<div style="display:block;width:100%;height:10px;background-color:#56CBFD;"></div>';

It works for EDM and Hip-Hop, but stops working after Hip-Hop. 它适用于EDM和Hip-Hop,但在Hip-Hop之后停止工作。

Any help is greatly appreciated! 任何帮助是极大的赞赏!

What about this? 那这个呢?

$genre_colors = array("EDM" => "9B86FF", "Hip-Hop" => "56FFCE", "Rock" => "56CBFD");
$color = $genre_colors[get_post_meta($post->ID, 'genre', true)];
if ($color !== null)
  echo '<div style="display:block;width:100%;height:10px;background-color:#' . $color . ';"></div>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM