2012-03-30 108 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]); 
    }  
}