使用数组动态生成 switch 语句的 case
我正在创建一个脚本来自动为我的网站的各个部分生成 RSS 提要。我已通过数据库进行查询,并有一个数据数组,代表名为 $showData
的每个部分。我使用 switch
语句根据网站的部分设置各种变量。我希望 switch
语句中的 case
是动态的,而不是每次添加节目时都必须更改此脚本。
<?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;
}
?>
我尝试使用 foreach
循环来创建每个案例,但您不能将其放入 switch
语句中。我在另一篇文章中读到的其他人建议使用eval()
。
这是我尝试过的代码,但不起作用。
<?php
switch($showFilter)}
foreach($showFilters as $key => $value){
case $key:
$title = $value;
$description = $value;
break;
}
}
?>
这是数组的 print_r
Array
(
[show1] => The Name of Show One
[show2] => The Name of Show Two
)
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
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了使用
switch
块,您是否可以尝试:Instead of using a
switch
block, could you not just try: