简体   繁体   English

检查数组是否具有一个或多个空键,而不是删除父数组

[英]Check if array has one or more empty keys than remove parent array

I have an multidimensional array (key - value), and some values are not set, empty in this case, if so the parent array must be removed from the main array. 我有一个多维数组(键-值),并且未设置某些值,在这种情况下为空,如果是这样,则必须从主数组中删除父数组。

The code that I have build only removes the empty key. 我建立的代码只删除了空键。

In my example the IT & ES language translation keys are empty so we need to removed this parent array. 在我的示例中,IT和ES语言翻译键为空,因此我们需要删除此父数组。

$results = $arr =array(
    [16] => Array
        (
            [0] => Array
                (
                    [language] => de
                    [translation] => blog/beer
                )

            [1] => Array
                (
                    [language] => en
                    [translation] => blog/some-slug-yeah
                )

            [2] => Array
                (
                    [language] => es
                    [translation] => 
                )

            [3] => Array
                (
                    [language] => fr
                    [translation] => blog/paris-big-city
                )

            [4] => Array
                (
                    [language] => it
                    [translation] =>
                )

            [5] => Array
                (
                    [language] => nl
                    [translation] => blog/nederlands-slug
                )

        )

        [...]//more
)

Function to remove keys. 删除按键的功能。

        function array_filter_recursive($input){
            foreach ($input as &$value){
                if (is_array($value)){
                    $value = array_filter_recursive($value);
                }
            }
            return array_filter($input);
        }

        $results  = array_filter_recursive( $results );

If the array always has 2 levels, you don't need recursion. 如果数组始终具有2个级别,则不需要递归。

 function array_filter_recursive($input){
        foreach ($input as &$value){
            $value = array_filter($value, function($x) { return !empty($x['translation']); });
        }
        return $input;
    }

demo 演示

If your structure is always going to be like this: 如果您的结构总是这样:

$arr = (
        [0] => Array
            (
                [language] => de
                [translation] => blog/beer
            )

        [1] => Array
            (
                [language] => en
                [translation] => blog/some-slug-yeah
            )

you can do this: 你可以这样做:

for($i = 0; $i < count($arr); $i++}
    if(!isset($arr[$i]["translation"]){
        unset($arr[$i])
    }
}

//re-index thee array;
$arr = array_values($arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM