【问题标题】:PHP switch case for varying url用于不同 url 的 PHP 切换案例
【发布时间】:2012-06-15 10:41:30
【问题描述】:

我正在 CodeIgniter 框架上构建一个站点,并且我正在使用 PHP 开关来加载与页面相关的特定 javascript。当我到达第三个 URI 段时,我的问题就出现了,这通常是一个变量。例如我对说没有问题

case 'foo/bar':

但是,如果我的 url 类似于 http://mysite.com/foo/bar/1234,其中 1234 如果变量传递给控制器​​怎么办。为每个变量写一个案例显然是没有意义的,因为现在大约有 30k。

目前这是我的代码的工作 sn-p...

switch( $this->uri->uri_string() ) {

            case '': 

            break;

            case 'browse':

            break;

            case 'contest/leaderboard':

【问题讨论】:

    标签: php codeigniter switch-statement


    【解决方案1】:

    您还可以在正斜杠上分解 url,然后检查数组的每个元素。

    例如

    $url_parts = explode('/', $this->uri->uri_string());
    switch($url_parts[0]){
      case 'foo':
         if(count($url_parts) > 1){
           if($url_parts[1] == "bar"){
             // when the url begins with foo/bar
           }
         }
         break;
       case 'browse':
         //when url is browse
       break;
    }
    

    这样做的好处是您可以包含所有以 foo 开头的 url 通用的代码。不确定这是否是必需的,但可能有用

    【讨论】:

      【解决方案2】:

      那么你使用“开始于”条件:

      $uri = $this->uri->uri_string();
      if (0 === strpos($uri, 'foo/bar')) {
          // starts with foo/bar
      } elseif (0 == strpos($uri, .... etc
      

      【讨论】:

        猜你喜欢
        • 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
        相关资源
        最近更新 更多