How to concatenate two or more arrays in PHP without loosing values if it is same key and different values -


i have 2 multi-dimensional arrays. need concatenate 2 without loosing values have same key , different values. here scenario:

array1 (     [0] => 11     [2] => 12     [3] => 13     [4] => (                 [0] =>  100                 [1] =>  200             )     [5] => 2     [6] => 3 )  array2 (     [0] => 11     [2] => 12     [3] => 13     [4] => (                 [0] =>  400                 [1] =>  500             )     [5] => 2     [6] => 3 ) 

the result should

result (     [0] => 11     [2] => 12     [3] => 13     [4] => (                 [0] =>  (                             [0] => 100                             [1] => 400                         )                 [1] =>  (                             [0] => 200                             [1] => 500                         )             )     [5] => 2     [6] => 3 ) 

here 1 solution:

<?php $arraya = array(0 => 11, 2 => 12, 3 => 13, 4 => array(0 => 100, 1 => array(0 => 222),), 5 => 2, 6 => 3); $arrayb = array(     0 => 11,     2 => 12,     3 => 13,     4 => array(         0 => 100,         1 => array(0 => array(0 => 'test1', 1 => 'test2'), 1 => array(0 => 'test1', 1 => 'test2'),),     ),     5 => 2,     6 => 3 );   /**  * @param $a  * @param $b  * @return array  */ function array_merge_graceful($a, $b) {     $c = [];     if (is_array($a) && is_array($b)) {         foreach (array_merge(array_keys($a),array_keys($b)) $i) {             if (!array_key_exists($i, $a)) {                 $c[$i] = $b[$i];             } elseif (!array_key_exists($i, $b)) {                 $c[$i] = $a[$i];             } else {                 $c[$i] = array_merge_graceful($a[$i], $b[$i]);             }         }     } else {         if ($a <> $b) {             $c = [$a, $b];         } else {             $c = $a;         }     }     return $c; }  var_dump(array_merge_graceful($arraya, $arrayb));  ?> 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -