如何用php中的键删除空数组值?

时间:2017-09-22 11:49:35

标签: php arrays

我得到的数组类似于以下数组。

{"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(),但它没有帮助。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

尝试以下代码,

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

答案 2 :(得分: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