0

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.

$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 );

2 Answers 2

1

If the array always has 2 levels, you don't need recursion.

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

demo

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.