【问题标题】:auto switch cases from *.php file*.php 文件中的自动切换案例
【发布时间】:2017-06-14 12:57:03
【问题描述】:

我正在尝试从文件夹中获取文件并将它们添加到 switch case,这可能吗?

如果可能的话,我只想使用文件名以防万一,但是当我回显它们时,它们就像“/etc/folder/otherfolder/filename.php”这个...

我试图修剪和爆炸它们,但我做不到。

$files = glob("pages/" . "/*.*");

for ($i=0; $i<count($files); $i++) {            
    $ext = strtolower(pathinfo($files[$i], PATHINFO_EXTENSION));
    echo $files[$i] . '<br/>';
    switch($section){
        case $files[$i]:
            include_once $files[$i];
            break;
        default:
            include_once $files[0];
            break;
    }
} 

【问题讨论】:

  • 不知道你想在这里做什么。 $section 是什么?为什么需要将数组的第一个条目与其他条目区别对待?请在此处描述您真正想要实现的目标。
  • 我正在尝试将我所有的静态 php 文件用于用例...
  • 这并不能更好地解释它。
  • 我正在尝试使用 switch case 动态获取我的所有静态 php 文件
  • 重复同样的废话并不会使其更清晰。请在此处解释您要实现的目标 - 甚至不提及“切换”一词。

标签: php switch-statement case


【解决方案1】:

试试这个,这就是你要找的东西:

    $files = glob("pages/" . "/*.*");
                $file_found=0;     //found variable
                for ($i=0; $i<count($files); $i++) {

                    $ext = strtolower(pathinfo($files[$i], PATHINFO_EXTENSION));
                    $file = basename($files[$i]);         // $file is set to "example.php"
                    $file = basename($files[$i], ".php"); // $file is set to only "example"
                    echo $file . '<br/>';

                    switch($section){
                        case $file:         //campares only filename without extension
                            include_once $files[$i];  //includes using the full path
                        $found=1;  //case matched
                        break;
                        case "all":
                            foreach (glob("pages/*.php") as $filename) //loops every file and include each one
                            {
                                include $filename;
                            }
                        $found=1; //case matched
                        break;  

                    }
                } 
               if(!$found)
                  include_once($files[$0]);

【讨论】:

  • 是的,这就是我想要的,非常感谢它正在工作,但默认情况下每个案例页面都会出现......
  • 由于您的开关在循环内,因此开关正在获取一个匹配参数,而所有其他参数都不匹配,因此它执行默认情况。
  • 删除默认大小写并使用 $found 变量。我已经编辑了答案,尝试一下,如果可行,则接受答案。
  • 哦,有什么问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多