2017-09-22 93 views
-2

我得到一個類似於下列數組的數組。如何在PHP中用鍵刪除空數組值?

{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]} 

如果表單數據值null,我想下一個鍵的值來代替該鍵的值。 像上面那樣,在值5之後,我有空值。它需要是這樣的:

"final_data":["1","2","4","5","fill this with 6","remove this"] 
"final_data":["1","2","4","5","6"] like this 

我試過array_filter(),但它沒有幫助。

+0

輸出'的array_flter'功能 –

+2

可能重複[刪除空數組元件](HT tps://stackoverflow.com/questions/3654295/remove-empty-array-elements) – Script47

回答

1

下面的代碼試試,

foreach($myarray as $key=>$value) 
{ 
    if(is_null($value) || $value == '') 
     unset($myarray[$key]); 
} 
+1

考慮['trim'](http://php.net/manual/en/function.trim.php)。 – Script47

2

如果響應是JSON格式,然後...

$json = '{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}'; 
$array = json_decode($json, TRUE); 

foreach($array as $index => $a) { 
    $array[$index] = array_filter($a); 
} 

print_r($array); 

https://eval.in/866379


更新

foreach($array as $index => $a) { 
    $array[$index] = array_value(array_filter($a)); 
} 

https://eval.in/866522

+0

@MassoodUrRehman謝謝 但在你的例子中可能的索引值可以是4而不是5 – Bhautik

+0

是的,你可以使用array_value()對array_filter()的響應來重新索引結果數組。 – MasoodUrRehman

0

試試這個array_filter()array_map()array_values()

<?php 
    $array = array("form_data" => array("1","2","4","5","","6"), "final_data" => array("1","2","4","5","","6")); 
    function filterMe($paraArr){ 
     return array_values(array_filter($paraArr)); 
    } 
    $array = array_map("filterMe",$array); 
    echo "<pre>"; 
    print_r($array); 

檢查這裏https://eval.in/866401