CodeIgniter-可选参数 [英] CodeIgniter - Optional parameters
问题描述
我正在构建我的第一个CodeIgniter应用程序,并且需要创建如下URL:
I'm building my first CodeIgniter application and I need to make URLs like follows:
controllername/{uf}/{city}
示例:/rj/rio-de-janeiro 这个例子应该给我两个参数:$ uf('rj')和$ city('rio-de-janeiro')
Example: /rj/rio-de-janeiro This example should give me 2 parameters: $uf ('rj') and $city ('rio-de-janeiro')
另一个网址可能是:
controllername/{uf}/{page}
示例:/rj/3 这个例子应该给我两个参数:$ uf('rj')和$ page(3)
Example: /rj/3 This example should give me 2 parameters: $uf ('rj') and $page (3)
换句话说,参数"city"和"page"是可选的. 我无法传递"/uf/city/page"之类的信息.我需要始终或城市"或页面". 但是我不知道如何在CodeIgniter配置中将这些路由配置为指向相同的方法(甚至指向不同的方法).
In other words, the parameters "city" and "page" are optionals. I can't pass something like '/uf/city/page'. I need always or 'city' OR 'page'. But I don't know how to configure these routes in CodeIgniter configuration to point to same method (or even to different methods).
推荐答案
我找到了正确的结果:
$route['controllername/(:any)/(:any)/(:num)'] = 'ddd/index/$1/$2/$3';
$route['controllername/(:any)/(:num)'] = 'ddd/index/$1/null/$2'; // try 'null' or '0' (zero)
$route['controllername/(:any)'] = 'ddd/index/$1';
Index方法(在"ControllerName"内部)应为:
The Index method (inside "ControllerName") should be:
public function Index($uf = '', $slug = '', $pag = 0)
{
// some code...
if (intval($pag) > 0)
{
// pagination
}
if (!empty($slug))
{
// slug manipulation
}
}
希望它可以帮助某人. 谢谢大家.
Hope it helps someone. Thank you all.
这篇关于CodeIgniter-可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!