简体   繁体   中英

Unset array key if value is empty

Array
(
    [2] => Array
        (
            [option_id] => 2
            [price] => 15
            [processor] => Array
                (
                    [3] => Array
                        (
                            [processor_id] => 3
                            [price] => 15
                        )

                    [4] => Array
                        (
                            [processor_id] => 4
                            [price] => 15
                        )

                )

        )

    [3] => Array
        (
            [option_id] => 3
            [price] => 15
            [processor] => Array
                (
                    [3] => Array
                        (
                            [processor_id] => 3
                            [price] => 15
                        )

                    [4] => Array
                        (
                            [processor_id] => 4
                            [price] => 15
                        )

                )

        )

    [4] => Array
        (
            [processor] => Array
                (
                    [3] => Array
                        (
                            [price] => // empty value
                        )

                    [4] => Array
                        (
                            [price] => // empty value
                        )

                )

        )

)

I have this array, Now I want to unset the array which array doesn't have any value like in the last array there is no value given so I want to unset the whole array key.

In This array, i have empty value so how can i unset the [4] key. So is it possible without foreach loop.

You can use array_filter for this. As you supplied no code I recommend reading the documentation on php.net.

function filter_function($var) {
    // return an expression evaluating to true to keep value
    return ($var["option_id"]);
}

$filtered = array_filter($unfiltered, "filter_function");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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