2012-03-30 3 views
1

Я использую cakephp 2.0, и у меня есть данные, которые я хочу очистить, структура массива ниже, как удалить элемент (quoteitem), где количество = null?php удалить элемент из массива

У меня есть это, но он не работает;

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

структура массива называется ($ this-> request-> данные)

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 –

+0

спасибо, черт возьми, я был близок :) –

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]); 
    }  
} 
Смежные вопросы