如何获取数组的参数类型


How to getParams type of array

在Magento中,我们通常使用参数

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);

恐怕目前不可能为Zend框架或Magento传递数组参数到Zend url。

这里报告了一个将get变量作为数组传递的错误。

如果您的意思是将所有参数作为一个数组(可能是一个可变对象):

$params = $this->getRequest()->getParams();

您也可以在查询参数上使用括号,如http://magento.com/customer/account/view/?id[]=123&id[]=456

则运行以下命令后,$x将是一个数组。

$x = $this->getRequest()->getParam('id');

我的建议,如果你想从访问者的输入作为数组,然后,而不是通过URL作为GET参数传递它们作为POST变量。

$params = $this->getRequest()->getParams();

在Zend Framework 1.12中,这可以通过getParam()方法实现。注意getParam()的结果对于没有可用的键是NULL,对于1个键是一个字符串,对于多个键是一个数组:

没有'id'值

http://domain.com/module/controller/action/
$id = $this->getRequest()->getParam('id');
// NULL

单个'id'值

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 = $this->getRequest()->getParam('id');
if($id !== null && !is_array($id)) {
    $id = array($id);
}
http://domain.com/module/controller/action/
// NULL
http://domain.com/module/controller/action/id/122
// array(1) { [0]=> string(3) "122" }

如果总是希望$id是数组(如果没有设置则没有NULL值,只是空数组):

$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" }

同上一行(没有NULL,总是数组):

$id = (array)$this->getRequest()->getParam('id');

如果您希望$id为字符串 (第一个可用的值,保持NULL完整)

$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是字符串 (最后可用的值,保持NULL完整)

$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"

也许有更短/更好的方法来修复这些getParam的"响应类型",但如果你要使用上面的脚本,它可能更干净,为它创建另一个方法(扩展助手或其他东西)。