0

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);
3
  • 3
    Have you looked or thought about any way to do this? Commented Aug 22, 2014 at 17:08
  • added a possible solution Commented Aug 22, 2014 at 17:23
  • You have 3 dimensional arrays always? Commented Aug 22, 2014 at 17:23

2 Answers 2

1

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.

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

2 Comments

How do I remove duplicates in an array with associative key value pairs?
Duplicate keys or duplicate keys with duplicate values?
0
  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).

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.