2010-11-21 58 views
3

我目前使用CodeIgniter。CodeIgniter - 无限参数?

我想写一个函数,可以采取无限数量的参数。

所以在控制它会像

function test($name, $others){ 
    foreach($others){ 
     //do something 
    } 
} 

,我可以这样称呼它

example.com/control/test/some name/param1/param2/param3/param4/param5... 

我如何设置呢?

回答

6

您可以使用URI class中的uri_to_assoc函数获取关联的URI段数组。所以,在你的控制器,你可以做这样的事情:

function test($name){ 
    $uri_seg = $this->uri->uri_to_assoc(4); 

    foreach($uri_seg as $para){ 
     // Do something with each of the URI segments passed in here after $name 
    } 
} 
+0

干杯, 是否有一个获得非关联数组? 所以,只需一个数组('param1','param2','param3','param4','param5');'? – Hailwood 2010-11-21 09:59:46

+1

@Haiwood我认为'segment_array()'函数应该做到这一点 – 2010-11-21 10:01:38

+0

为什么不使用php的本地[func_get_args](http://php.net/manual/en/function.func-get-args.php) – dsdsdsdsd 2016-05-23 14:45:14

6

你也可以做这样的:

function foo($params=array()) 
{ 
    $params=func_get_args(); 
    //print_r($params); 
} 

所以任何网址,如:

site.com/controller/foo/param1/param2/param3/param4

将创建一组参数。

0

目前尚不清楚为什么您需要无限(可变)数量的参数,但您可能需要考虑为什么需要它们。

对于某些类型的参数,您可以使用替代URI语义。通常,URI设计是系统中事物的路径。无限参数可能不涉及资源,而是描述其属性。标签就是一个很好的例子。

/chicken/red+tall+fat 

使用单个参数轻松实现CodeIgniter中的标签实现。

如果参数是指一个节点,你可以考虑类似的方法:

/hen-house.bunk4.topshelf/chicken 

或者,如果作为路径,你可以使用上面的func_get_args()解决方案的层次是非常重要的。

+0

例如:你的应用程序有一个清单(待售房屋清单),而且用户界面允许用户用关键词(例如“车库,2房,阳台,中央空调,壁炉”)过滤清单......如果您可以将这些过滤词分配给网址,那么您可以轻松地将链接发送到过滤列表(“www.example.com/garage/2bedrooms/balcony/central air/fireplace”) – dsdsdsdsd 2016-05-23 14:49:50