如何在数组中查找和替换空值?

时间:2014-04-07 02:22:33

标签: php arrays

例如,我有一个数组

Array(
[0] => Array
    (
        [0] => "0"
        [1] => "1"
    )
[1] => 
[2] => Array
    (
        [4] => "4"
        [5] => "5"
        [7] => "7"
    )

我希望找到空数组值,并替换它。

[1] => data not found

2 个答案:

答案 0 :(得分:4)

非递归:

$arr = array(
    0 => array(
        0 => "0",
        1 => "1"
    ),
    1 => "",
    2 => array(
        4 => "4",
        5 => "5",
        7 => "7"
    ),
    3 => array(
        8 => "",
        9 => ""
    )
);

foreach($arr as &$val){
if($val === "" || $val === false || $val === null) $val = "data not found";
}

print_r($arr);

DEMO

递归:

function replace_empty_values($arr){
    foreach($arr as &$val){
    if(is_array($val)) $val = replace_empty_values($val);
    else if($val === "" || $val === false || $val === null) $val = "data not found";
    }
return $arr;
}

$arr = array(
    0 => array(
        0 => "0",
        1 => "1"
    ),
    1 => "",
    2 => array(
        4 => "4",
        5 => "5",
        7 => "7"
    ),
    3 => array(
        8 => "",
        9 => ""
    )
);

$arr = replace_empty_values($arr);
print_r($arr);

DEMO

答案 1 :(得分:0)

这是一个递归解决方案。

$myArray = array(
    0 => array(
        0 => "0",
        1 => "1"
    ),
    1 => "",
    2 => array(
        4 => "4",
        5 => "5",
        7 => "7"
    )
);

function removeEmpty($arr){
    if(is_array($arr)){
        foreach($arr as &$val){
             $val = removeEmpty($val);
        }
        return $arr;
    }
    else {
        if(empty($arr) && $arr != "0") return "data not found";
    }
}

print_r(removeEmpty($myArray));