5

Current array:

Array (
    [name] => Array (
        [name1] => Array (
            [0] => some value1
        )
        [name2] => Array (
            [0] => some value2
        )
        [name3] => Array (
            [0] =>
        )
) 

Wanted array:

Array (
    [name] => Array (
        [name1] => Array (
            [0] => some value1
        )
        [name2] => Array (
            [0] => some value2
        )
) 

Since name3[0] doesn't contain any value, it needs to be removed. From what I read, I should use array_filter for this, but I can't get it to work.

4

3 回答 3

5

您需要提供array_filter一个谓词(函数)来确定[0]每个数组元素的子元素是否为空。所以:

$array = array_filter($array, function($item) { return !empty($item[0]); });

请注意,这empty不是很挑剔:它会导致删除其[0]子元素为空字符串、、、false或的null任何项目——它还将删除根本没有子元素的项目。如果您需要更有针对性的手术,则需要对测试进行微调。0"0"[0]

于 2013-07-25T21:25:24.700 回答
5

递归函数,它将从输入数组中删除所有空值和空数组:

//clean all empty values from array
function cleanArray($array)
{
    if (is_array($array))
    {
        foreach ($array as $key => $sub_array)
        {
            $result = cleanArray($sub_array);
            if ($result === false)
            {
                unset($array[$key]);
            }
            else
            {
                $array[$key] = $result;
            }
        }
    }

    if (empty($array))
    {
        return false;
    }

    return $array;
}

我已经在这个例子中测试过了,不管数组有多深,它都可以工作:

$array = array(
    'name' => array(
        'name1' => array(0 => 1),
        'name2' => array(0 => 3, 1 => array(5 => 0, 1 => 5)),
        'name3' => array(0 => '')
    )
);

希望这可以帮助 :)

于 2013-07-25T21:53:01.157 回答
2

可以使用递归函数来完成:

$arr = array('test', array('',0,'test'), array('',''));

print_r(clean_array($arr));

function clean_array($array, $isRepeat = false) {
    foreach ($array as $key => $value) {
        if ($value === null || $value === '') { unset($array[$key]); }
        else if (is_array($value)) {
            if (empty($value)) { unset($array[$key]); }
            else $array[$key] = clean_array($value);
        }
    }
    if (!$isRepeat) {
        $array = clean_array($array,true);
    }
    return $array;
}
于 2013-07-25T21:36:52.203 回答