简体   繁体   中英

Dynamically generate cases for switch statement using an array

I'm creating a script to auto generate an RSS feed for the various sections of my website. I've queried by database and have an array of data which represents each section called $showData . I'm using a switch statement to setup various variables depending upon the section of the site. Instead of having to change this script each time I add a show, I'd like the case in my switch statement to be dynamic.

<?php
switch($section){
    case 'show1':
        $title = $showData['show1'] . ' Title';
        $description = $showData['show1'] . ' Description';
        break;
    case 'show2':
        $title = $showData['show2'] . ' Title';
        $description = $showData['show2'] . ' Description';
        break;
}
?>

I attempted to use a foreach loop to create each case, but you can't put that inside a switch statement. Someone else in another post I read suggested using eval() .

Here's my code that I tried, that doesn't work.

<?php
switch($showFilter)}
    foreach($showFilters as $key => $value){
        case $key:
        $title = $value;
        $description = $value;
        break;
    }
}
?>

Here's a print_r of the array

Array
(
    [show1] => The Name of Show One
    [show2] => The Name of Show Two
)

Instead of using a switch block, could you not just try:

$title = $showData[$section] . ' Title';
$description = $showData[$section] . ' Description';

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