2012-03-30 181 views
1

我使用cakephp 2.0和我有數據提交,我想清理,數組結構是如何刪除元素(quoteitem)數量= null?從數組中刪除元素

我有這個,但它不工作;陣列的

foreach($this->request->data['Quoteitem'] as $qi) { 
if($qi['quantity']==null){ 
echo 'quantity is null,delete this quote item from array';     
unset($qi); 
}  
} 

結構,稱爲($這個 - >請求 - >數據)

Array 
(
    [Quote] => Array 
     (
      [customer_id] => 72 
      [user_id] => 104     
     ) 

    [Range] => Array 
     (
      [id] => 
     ) 

    [Quoteitem] => Array 
     (
      [0] => Array 
       (
        [product_id] => 
        [unitcost] => 
        [quantity] => 1 
       ) 

      [1] => Array 
       (
        [product_id] => 
        [unitcost] => 
        [quantity] => 22 
       ) 

      [2] => Array 
       (
        [product_id] => 339 
        [unitcost] => 5 
        [quantity] => 
       )  

     ) 

) 

回答

5

您可以使用數組鍵將其刪除:

foreach($this->request->data['Quoteitem'] as $key => $qi) { 
    if($qi['quantity'] == null){ 
     echo 'quantity is null,delete this quote item from array';     
     unset($this->request->data['Quoteitem'][$key]); 
    }  
} 

注意,這將創建空白在數組中(不存在的索引),通常這不會成爲問題,但如果是這樣的話,您可以使用array_values()重新索引數組。

+0

哈哈,贏家。確切的解決方案,我鍵入:x – 2012-03-30 15:05:11

+0

謝謝,該死的我很接近:) – 2012-03-30 15:08:32

1

的foreach進行復印時,試試這個:

foreach($this->request->data['Quoteitem'] as $key => $qi) { 
    if($qi['quantity']==null){ 
     echo 'quantity is null,delete this quote item from array';     
     unset($this->request->data['Quoteitem'][$key]); 
    }  
}