Php 如何获取数组的params类型
在Magento,我们通常会得到paramPhp 如何获取数组的params类型,php,magento,url,parameters,param,Php,Magento,Url,Parameters,Param,在Magento,我们通常会得到param http://magento.com/customer/account/view/id/122 我们可以通过 $x = $this->getRequest()->getParam('id'); echo $x; // value is 122 现在据我所知,$x只是为了从参数中获取字符串 有没有办法将$x作为数组获取 例如: Array ( [0] => 122 [1] => 233 ) 例如: http:
http://magento.com/customer/account/view/id/122
我们可以通过
$x = $this->getRequest()->getParam('id');
echo $x; // value is 122
现在据我所知,$x只是为了从参数中获取字符串
有没有办法将$x作为数组获取
例如:
Array
(
[0] => 122
[1] => 233
)
例如:
http://magento.com/customer/account/view/id/122-233
$x = $this->getRequest()->getParam('id');
$arrayQuery = array_map('intval', explode('-', $x)));
var_dump($arrayQuery);
如果您的意思是将所有参数作为数组获取(可能是varien对象):
恐怕Zend Framework或Magento目前无法将数组参数传递给Zend url
这里有一个错误报告 我的建议是,如果希望访问者的输入作为数组传递,那么不要将它们作为GET参数传递到URL中,而是将它们作为POST变量传递
然后$_POST将拥有所有,您可以使用$params=$this->getRequest()->getParams() 您还可以在查询参数上使用括号,如http://magento.com/customer/account/view/?id[]=123&id[]=456 然后在运行以下命令之后,$x将是一个数组
$x = $this->getRequest()->getParam('id');
在Zend Framework 1.12中,仅使用getParam()方法就可以实现这一点。请注意,getParam()的结果对于无可用键为NULL,对于1键为字符串,对于多键为数组: 没有“id”值
http://domain.com/module/controller/action/
$id = $this->getRequest()->getParam('id');
// NULL
http://domain.com/module/controller/action/id/122
$id = $this->getRequest()->getParam('id');
// string(3) "122"
单个“id”值
http://domain.com/module/controller/action/
$id = $this->getRequest()->getParam('id');
// NULL
http://domain.com/module/controller/action/id/122
$id = $this->getRequest()->getParam('id');
// string(3) "122"
多个“id”值:
http://domain.com/module/controller/action/id/122/id/2584
$id = $this->getRequest()->getParam('id');
// array(2) { [0]=> string(3) "122" [1]=> string(4) "2584" }
如果您总是希望代码中包含字符串,并且出于某种原因,url中设置了更多的值,那么这可能会出现问题:例如,在某些情况下,您可能会遇到错误“数组到字符串的转换””。以下是一些避免此类错误的技巧,以确保始终从getParam()获得所需的结果类型:
如果希望$id是数组(如果未设置参数,则为NULL)
如果始终希望$id是数组(如果未设置,则无空值,仅空数组):
在一行中与上述内容相同(无空,始终为数组):
如果希望$id是字符串(第一个可用的值保持NULL不变)
如果希望$id是字符串(上次可用的值保持NULL不变)
也许有更简短/更好的方法来修复getParam的这些“响应类型”,但是如果您要使用上述脚本,那么为其创建另一个方法(ExtendedHelper或其他方法)可能会更简洁
$id = $this->getRequest()->getParam('id');
if(!is_array($id)) {
if($id === null) {
$id = array();
} else {
$id = array($id);
}
}
http://domain.com/module/controller/action/
// array(0) { }
http://domain.com/module/controller/action/id/122
// array(1) { [0]=> string(3) "122" }
$id = (array)$this->getRequest()->getParam('id');
$id = $this->getRequest()->getParam('id');
if(is_array($id)) {
$id = array_shift(array_values($id));
}
http://domain.com/module/controller/action/
// NULL
http://domain.com/module/controller/action/122/id/2584
// string(3) "122"
$id = $this->getRequest()->getParam('id');
if(is_array($id)) {
$id = array_pop(array_values($id));
}
http://domain.com/module/controller/action/
// NULL
http://domain.com/module/controller/action/122/id/2584/id/52863
// string(5) "52863"