0

I have following array keys values:

$arrData = array
(
    array(
        'a' => 'test',
        'c' => 1,
        'd' => 2,
        'e' => 'B'
    ),
    array(
        'c' => 1,
        'd' => 2,
        'e' => 'B'
    ),
    array(
        'b' => 'test2',
        'c' => 1,
        'd' => 2,
        'e' => 'B'
    )
);

So here I need to merged array into single with combining missing keys with single value array. Can someone please help to get following output in single array?

$arrData = array
(
    array(
        'a' => 'test',
        'b' => 'test2',
        'c' => 1,
        'd' => 2,
        'e' => 'B'
    )
);

Thanking in advance!

Rahul
  • 18,271
  • 7
  • 41
  • 60

4 Answers4

6

Just merge them and then sort on the key:

$arrData = array_merge(...$arrData);
ksort($arrData);

Instead of ... you can use:

$arrData = call_user_func_array('array_merge', $arrData);

If you really want the result to be multi-dimensional, then:

$arrData = [$arraData];
//or
$arrData = array($arrData);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
4

You can use array_reduce (or a simple foreach loop) to merge each of the subsequent array values with the first one:

$out = array_reduce($arrData, function ($c, $v) { return array_merge($c, $v); }, array());
print_r($out);

$out = array();
foreach ($arrData as $arr) {
    $out = array_merge($out, $arr);
}
print_r($out);

Output (for both examples):

Array (
  [a] => test
  [c] => 1
  [d] => 2
  [e] => B
  [b] => test2 
)

If you want to keep the keys in alphabetical order, you can use ksort:

ksort($out);
print_r($out);

Array (
  [a] => test
  [b] => test2 
  [c] => 1
  [d] => 2
  [e] => B
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
  • 1
    That's the answer I was about to post. You can also use `ksort` to keep the keys in order (he seems to want that, tho I'm not sure this is mandatory). – Jeto May 20 '19 at 13:17
1

Using array_walk and ksort

$res=[];
array_walk($arrData, function($v,$k) use(&$res){
  $res = array_merge($res,$v);
});
ksort($res);

OR

You can use foreach and array_column

$keys = ['a','b','c','d','e'];
$res=[];
foreach($keys as $val){
   $res[$val] = array_column($arrData, $val)[0];
}
print_r($res);

Live Demo

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
0
<?php
  $arrData = array
(
    array(
        'a' => 'test',
        'c' => 1,
        'd' => 2,
        'e' => 'B'
    ),
    array(
        'c' => 1,
        'd' => 2,
        'e' => 'B'
    ),
    array(
        'b' => 'test2',
        'c' => 1,
        'd' => 2,
        'e' => 'B'
    )
);

$result_array = array();
foreach($arrData as $ad){

    foreach($ad as $key=>$value){


        if(!array_key_exists($key,$result_array)){
            $result_array[$key] = $value;
        }

    }
}

print_r($result_array);
?>
kalaivanan
  • 63
  • 8