【问题标题】:How to use a switch with a foreach loop如何使用带有 foreach 循环的开关
【发布时间】:2014-10-30 15:29:39
【问题描述】:

我有多个页面调用“特色项目”列表 - 我希望将特色项目包含在一个包含中,然后在我的其他页面上给出要包含在变量中的特色项目的名称。

我想也许可以使用一个开关然后一个 foreach 循环来运行它,但我是 PHP 新手,我不确定这样做是否正确。

所以我想像这样创建我的开关:

switch ($sector){
    case "Sector1":
        $title = "title of sector";
        $url = "url here";
        $img = "image url here";       
        break;
    case "Sector2":
        $title = "title of sector";
        $url = "url here";
        $img = "image url here";
        break;
    case "Sector3":
        $title = "title of sector";
        $url = "url here";
        $img = "image url here";
        break;    
    default:
        $title = "title of sector";
        $url = "url here";
        $img = "image url here";
        break;
}

然后在每个页面上我想声明我想使用哪个开关

例如,我想使用扇区 1 和 2,然后在 foreach 循环中运行它们,以便它们输出如下内容:

<div class="item">
    <h1>'.$title.'</h1>
    <img src="'.$img.'" />
</div>

我该怎么做呢?

【问题讨论】:

  • 你在使用数据库吗?如果没有,您似乎需要它
  • 只有 4/5 个项目可以切换,所以我想我可以把它放在一个开关盒中。
  • 他们改变了吗?如果没有,不要浪费你的时间,直接写HTML。
  • 你在正确的轨道上。为部分切换部分创建功能。从中返回数组。通过传递扇区参数调用函数并使用返回数组来渲染html块。
  • wonderwhy - 我更喜欢使用 php,因为我有 10 个页面调用不同的“特色项目” - 另外,学习如何做会很好:) kayra - 谢谢你的提示我不完全确定该怎么做

标签: php foreach switch-statement


【解决方案1】:

我认为没有理由使用开关盒。刚刚在数组中声明了您的项目,如下所示:

$Sectors = array("Sector1" => array("title" => "title of sector", "url" => "url here", "img" = "image url here"), 
  "Sector2" => array(...), 
 ...);

然后你可以得到任何特定的值,比如

$Sectors["Sector1"]["title"]

然后您可以只在每个页面上编写确切的 html 标签,或者像一个通用页面一样在顶部有一个您想要使用的数组

$Sectors_to_use = ["Sector1", "Sector2"];
foreach $Sectors_to_use as $sector {
    echo '<div class="item">';
    echo  "<h1>" . $Sectors[$sector]["title"] . "</h1>";
    echo  '<img src="' . $Sectors[$sector]["img"] . '"' />;
    echo "</div>"
}

【讨论】:

  • 谢谢你,这真的帮助了我!我不得不改变 $Sectors_to_use = ["Sector1", "Sector2"];到 $Sectors_to_use = array("Sector1", "Sector2");因为它不喜欢方括号,但你真的帮了我 - 谢谢! :)
猜你喜欢
  • 1970-01-01
  • 2016-12-09
  • 2017-03-25
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多