简体   繁体   中英

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. Each color represents a specific genre. I have 12 genres, but I've only included 3 of those for simplification purposes.

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($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.

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>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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