Codeigniter可变长度参数列表

EsT*_*eGe 4 php codeigniter

我正在使用Codeigniter创建一个教程系统,但我在使用子类别进行教程时有点困惑.

URL结构是这样的:/ tutorials/test/123/this-is-a-tutorial

  • 教程是控制器
  • test是该类别的短代码
  • 123是教程ID(在SQL查询中使用)
  • 这个教程只是一个美化URL的slu ..

我所做的是将类别作为第一个参数传递,将ID作为第二个参数传递给我的控制器函数:

public function tutorial($category = NULL, $tutorial_id = NULL);
Run Code Online (Sandbox Code Playgroud)

现在,如果我想要子类别(无限深度),比如:/ tutorials/test/test2/123/another-tutorial.我该如何实现?

谢谢!

Wes*_*rch 6

要阅读无限参数,您至少有两个有用的工具:

所以在你的控制器中:

  • 弹出最后一个段/参数(这是你的slug,不需要)
  • 假设最后一个参数是教程ID
  • 假设其余的是类别

像这样的东西:

public function tutorial()
{
    $args = func_get_args();
    // ...or use $this->uri->segment_array()

    $slug = array_pop($args);
    $tutorial_id = array_pop($args); // Might want to make sure this is a digit

    // $args are your categories in order
    // Your code here
}
Run Code Online (Sandbox Code Playgroud)

其余的代码和验证取决于您要对参数做什么具体的.

  • 在 PHP 5.6+ 中,您可以使用 ... 标记。比如:function sum(...$numbers) { foreach($numbers as $n) php.net/manual/en/functions.arguments.php (2认同)