Azriel Omega
Azriel Omega

Reputation: 939

Merge distinct multiple arrays to single array

Thing getting more difficult now. I have a query result like this:

Result = array(

A = array(
        [a]=>'1',
        [b] =>'2',
     );

B = array(
        [a] =>'1',
        [b] =>'3',
     );

C = array(
        [a] =>'1',
        [b] =>'4',
     );

**and more...**

);

So how can I merge them into one array like this:

Result = array(

     Z = array(

        [a] =>'1',
        [b] => array(

               [0] =>'2',
               [1] =>'3',
               [2] =>'4',
        );

     );

);

Thanks you and sorry for my poor presentation.

Upvotes: 1

Views: 166

Answers (3)

Aram Kocharyan
Aram Kocharyan

Reputation: 20421

If you plan to only have primitive values in the keys (strings, numbers etc.) this will work:

<?php

function array_combine_keys($a, $b) {
    $c = $a;
    foreach ($b as $k=>$v) {
        // Value can be only primitive, not an array itself
        if (isset($a[$k]) && $a[$k] !== $v) {
            $c[$k] = array($a[$k], $v);
        } else {
            $c[$k] = $v;
        }
    }
    return $c;
}

$a = array('a' => '1', 'b' => '2');
$b = array('a' => '1', 'b' => '3', 'c' => '5');

var_dump(array_combine_keys($a, $b));

?>

array(3) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  array(2) {
    [0]=>
    string(1) "2"
    [1]=>
    string(1) "3"
  }
  ["c"]=>
  string(1) "5"
}

A more versatile way is to allow arrays in the values as well, and to ensure the keys are always arrays irrespectively - this means we won't need extra logic to check if the key is an array or isn't an array when traversing the result. The (+) is the union of the two arrays.

<?php

function array_combine_keys($a, $b) {
    $c = $a;
    foreach ($b as $k=>$v) {
        if (!is_array($v)) {
            $v = array($v);
        }
        if (isset($a[$k])) {
            $av = $a[$k];
            if (!is_array($av)) {
                $av = array($av);
            }
            $c[$k] = $av + $v;
        } else {
            $c[$k] = $v;
        }
    }
    return $c;
}

$a = array('a' => '1', 'b' => array('2', '4'));
$b = array('a' => '1', 'b' => array('3'), 'c' => '5');

var_dump(array_combine_keys($a, $b));

?>

array(3) {
  ["a"]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  ["b"]=>
  array(2) {
    [0]=>
    string(1) "2"
    [1]=>
    string(1) "4"
  }
  ["c"]=>
  array(1) {
    [0]=>
    string(1) "5"
  }
}

Upvotes: 1

Dale
Dale

Reputation: 10469

I don't know why you keep asking the same question but here's my answer to your problem.

$result = array_merge_recursive($a, $b, $c);
foreach($result as $k => $v) $result[$k] = array_unique($v);
print_r($result);

Upvotes: 1

Venkata Krishna
Venkata Krishna

Reputation: 4305

You can look into array_merge function in PHP Manual

Upvotes: 2

Related Questions