简体   繁体   中英

Remove only associative array with all values empty

Is it possible to remove only the associative array who have all values empty?

Data source:

 Array
(
    [0] => Array
        (
            [name] => foo
            [phone] => 012345
            [email] => 
        )

    [1] => Array
        (
            [name] => bar
            [phone] => 
            [email] => yahoo.com
        )
    [2] => Array
        (
            [name] => 
            [phone] => 
            [email] => 
        )
)

Desired output:

Array
(
    [0] => Array
        (
            [name] => foo
            [phone] => 012345
            [email] => 
        )

    [1] => Array
        (
            [name] => bar
            [phone] => 
            [email] => yahoo.com
        )
)

I tried this, but unfortunately I will delete all empty values ​​of arrays

$_arr = array_filter(array_map('array_filter', $_arr));

Array
(
    [0] => Array
        (
            [name] => foo
            [phone] => 012345
        )

    [1] => Array
        (
            [name] => bar
            [email] => yahoo.com
        )
)

How could I do it? Thank You

Maybe a slicker way, but:

$array = array_filter($array, function($a) { return array_filter($a); });

Since array_filter is using a true or false return to filter; the array_filter in the function is returning either an empty array evaluated as false , or a non-empty array evaluated as true , and the main array_filter is filtering based upon that.

<?php 
$collection = array(
                    "0" => array
                        (
                            'name' => "foo",
                            'phone' => "012345",
                            'email' => ''
                        ),

                    "1" => array
                        (
                            'name' => "bar",
                            'phone' => '',
                            'email' => "yahoo.com",
                        ),
                    "2" => array
                        (
                            'name' => '',
                            'phone' => '',
                            'email' => ''
                        )
                );

foreach($collection as $key=> $entry){

    if(count(array_filter($entry)) == 0){
        unset($collection[$key]);
    }
}

print_r($collection);

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