简体   繁体   中英

Merge array values in a single array by removing duplicates and null values in PHP

I have an array like this:

Array
(
    [0] => Array
        (
             [0] => Array
                (
                    [id] => 1234
                    [name] => John
                )

             [1] => Array
                (

                )
        )

    [1] => Array
        (
            [0] => Array
                (
                    [id] => 1234
                    [name] => John
                )

            [1] => Array
                (
                    [id] => 5678
                    [name] => Sally
                )
            [2] => Array
                (
                    [id] => 1234
                    [name] => Duke
                )
)

My resulting array should be the following (basically merging and getting rid of duplicates and removing null values):

Array
(
    [0] => Array
        (
           [id] => 1234
           [name] => John
        )

    [1] => Array
        (
           [id] => 5678
           [name] => Sally
        )
    [2] => Array
        (
           [id] => 1234
           [name] => Duke
        )
)

Is there an easy way to do this using PHP's array functions?

EDIT: So far I have this:

$result = array();
      foreach ($array as $key => $value) {
        if (is_array($value)) {
          $result = array_merge($result, $value);
        }
      }
print_r($result);

Use array_merge to merge the arrays. Then use array_unique to remove duplicates. Finally, to remove null keys, use a loop.

foreach($array as $key=>$value)
{
    if(is_null($value) || $value == '')
        unset($array[$key]);
}

Documentation on these methods can be found here .

  1. Flatten your unnecessarily depth array structure by unpacking the subarrays into a merge call.
  2. Filter out the empty subarrays with array_filter() .
  3. Remove the duplicate subarrays with array_unique() . ( SORT_REGULAR prevents "Warning: Array to string conversion")

Code: ( Demo )

var_export(
    array_unique(
        array_filter(
            array_merge(...$array)
        ),
        SORT_REGULAR
    )
);
  1. Optionally, call array_values() on the resultant array to re-index it (remove the old keys).

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