2013-03-16 44 views
1

在Magento的,因爲通常我們用來獲取PARAM如何getParams陣列的類型

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 
) 

回答

4

例如:

http://magento.com/customer/account/view/id/122-233 

$x = $this->getRequest()->getParam('id'); 
$arrayQuery = array_map('intval', explode('-', $x))); 
var_dump($arrayQuery); 
3

如果你的意思是讓所有的參數作爲數組(可能是瓦瑞恩對象):

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

我的建議,如果你想從訪問者的數組作爲數組,然後而不是在URL中傳遞它們,因爲GET PARAMS將這些作爲POST變量傳遞。

然後$ _POST將所有,你可以$ params = $ this-> getRequest() - > getParams();

3

你也可以用你的查詢參數支架,像http://magento.com/customer/account/view/?id[]=123 & ID [] = 456

然後運行後,以下,$ x將是一個數組。

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

使用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" 

多「身份證」值:

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中設置:在某些情況下,例如,你可以運行進入錯誤「Array to string conversion」。這裏有一些技巧,以避免這樣的錯誤,以確保您始終獲得結果你getParam()不只需要的類型:

如果你想在$ ID是一個陣列(或NULL如果param未設置)

$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的'響應類型',但是如果你要使用上面的腳本,可以更清潔地爲它創建另一個方法(擴展的助手或其他)。