使用 Codeigniter 开发人员打算使用的方法实现此目的的两种好方法。
选项一:
如果您总是希望出现“id”参数,您可以利用在要调用的方法(函数)之后立即在 URI 中传递值的特性。
传递/[controller]/[method]/[value]的示例:
http://www.website.com/query/index/5
然后您将访问“id”的值作为函数的预期参数。
Class Query extends Controller {
...
// From your URL I assume you have an index method in the Query controller.
function index($id = NULL)
{
// Show current ID value.
echo "ID is $id";
...
}
...
}
选项二:
如果您希望除了 ID 之外还允许传递许多参数,您可以将所有参数作为键=>值对以任意顺序添加到 URI 段。
传递/[controller]/[method]/[key1]/[val1]/[key2]/[val2]/[key3]/[val3]的示例:
http://www.website.com/query/index/id/5/sort/date/highlight/term
然后,您将使用 URI 类中的 uri_to_assoc($segment) 函数将来自第 3 段(“id”)的所有 URI 段解析为键=>值对数组。
Class Query extends Controller {
...
// From your code I assume you are calling an index method in the Query controller.
function index()
{
// Get parameters from URI.
// URI Class is initialized by the system automatically.
$data->params = $this->uri->uri_to_assoc(3);
...
}
...
}
这将使您可以轻松访问所有参数,并且它们可以在 URI 中按任何顺序排列,就像传统的查询字符串一样。
$data->params 现在将包含一个 URI 段数组:
Array
(
[id] => 5
[sort] => date
[highlight] => term
)
一个和两个的混合体:
您还可以混合使用这些方法,其中 ID 作为预期参数传递,其他选项作为键 => 值对传递。当需要 ID 并且其他参数都是可选的时,这是一个不错的选择。
传递/[controller]/[method]/[id]/[key1]/[val1]/[key2]/[val2]的示例:
http://www.website.com/query/index/5/sort/date/highlight/term
然后,您将使用 URI 类中的 uri_to_assoc($segment) 函数将第 4 段(“排序”)中的所有 URI 段解析为键=>值对数组。
Class Query extends Controller {
...
// From your code I assume you are calling an index method in the Query controller.
function index($id = NULL)
{
// Show current ID value.
echo "ID is $id";
// Get parameters from URI.
// URI Class is initialized by the system automatically.
$data->params = $this->uri->uri_to_assoc(4);
...
}
...
}
$id 将包含您的 ID 值,$data->params 将包含您的 URI 段数组: