2013-11-14 100 views
0

我想過濾多維數組的一部分。我已使用array_filter函數。當我打印過濾的數據時,它顯示正確,但我似乎無法將數據保存回數組。多維數組的過濾部分

這裏是多維數組(稱爲$posted_product_details)預先含有內部陣列([data]),我想濾波器:

Array 
(
[column_1] => Array 
    (
     [name] => Colour 
     [data] => Array 
      (
       [0] => Blue 
       [1] => Green 
       [2] => Red 
       [3] => Yellow 
       [4] => 
       [5] => 
       [6] => 
       [7] => 
       [8] => 
       [9] => 
      ) 

    ) 

[column_2] => Array 
    (
     [name] => Pack QTY 
     [data] => Array 
      (
       [0] => 3 
       [1] => 3 
       [2] => 3 
       [3] => 3 
       [4] => 
       [5] => 
       [6] => 
       [7] => 
       [8] => 
       [9] => 
      ) 

    ) 

[column_3] => Array 
    (
     [name] => Product Code 
     [data] => Array 
      (
       [0] => 65030 
       [1] => 65029 
       [2] => 65028 
       [3] => 65031 
       [4] => 
       [5] => 
       [6] => 
       [7] => 
       [8] => 
       [9] => 
      ) 

    ) 

[column_4] => Array 
    (
     [name] => Barcode 
     [data] => Array 
      (
       [0] => 5099570650307 
       [1] => 5099570650291 
       [2] => 5099570650284 
       [3] => 5099570650314 
       [4] => 
       [5] => 
       [6] => 
       [7] => 
       [8] => 
       [9] => 
      ) 

    ) 

[column_5] => Array 
    (
     [name] => 
     [data] => Array 
      (
       [0] => 
       [1] => 
       [2] => 
       [3] => 
       [4] => 
       [5] => 
       [6] => 
       [7] => 
       [8] => 
       [9] => 
      ) 

    ) 

) 

在這裏,我通過陣列嘗試迴路和過濾數據:

foreach ($posted_product_details as $column => $info) { 
    $name = $info['name']; 
    $data = $info['data']; 
    $info['data'] = array_filter($data); 
} 

但是,以後打印數組時,數組並沒有改變。

回答

1

按引用傳遞的值修改原來的數組:

foreach ($posted_product_details as $column => & $info) { 
    $name = $info['name']; 
    $data = $info['data']; 
    $info['data'] = array_filter($data); 
} 

這將正確地過濾您的陣列的data一部分。但是,如果您需要過濾更深的元素,則必須使用遞歸功能,例如this one

Demo!

0

foreach構造使得每片陣列的的副本作爲你迭代它。你必須明確地調用原始數組來編輯它:

$posted_product_details[$column]['data'] = array_filter($data);