5

Possible Duplicate:
PHP: Merge 2 Multidimensional Arrays

I have these arrays and I want to merge them into one array.

$arrayAAA[0]['name'] = "stackoverflow";
$arrayBBB[0]['color'] = "white";
$arrayCCC[0]['media'] = "web";

I want to merge these like this.

$newArray[0]['name'] //"stackoverflow"
$newArray[0]['color'] //"white"
$newArray[0]['media'] //"web"

If anyone knows how to do this, please give me a help. I thought I could merge them by using array_merge(), but this function doesn't work in my case.

Thanks so much in advance!

Community
  • 1
  • 1
crzyonez777
  • 1,789
  • 4
  • 18
  • 27

4 Answers4

6

I dont know how much time you have wasted finding the solution while you could have written a manual one.

foreach(array($arrayAAA, $arrayBBB, $arrayCCC) as $v){
    foreach($v as $iv){
        $result[key($iv)] = $iv[key($iv)];
    }
}

CodePad

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
4

I think you want to use array_merge(), not merge_array()

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
3

So, this does not work either?

$x = array();
$x[0] = array_merge($arrayA[0], $arrayB[0], ...);

There is also array_merge_recursive function. But I am pretty sure it would only append each sub-array.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
dualed
  • 10,262
  • 1
  • 26
  • 29
2

For more complex arrays this should work, but seems like there should be an easier way.

$arrayAAA[0]['name'] = "stackoverflow";
$arrayBBB[0]['color'] = "white";
$arrayCCC[0]['media'] = "web";

function merge_arrays(){
    $aArgs = func_get_args();

    $aReturn = array();
    if($aArgs != array()){
        foreach($aArgs as $aArr){
            foreach($aArr as $mKey => $aSub){
                if(!isset($aReturn[$mKey])){
                    $aReturn[$mKey] = array();
                }

                foreach($aSub as $mSubKey => $mVal){
                    $aReturn[$mKey][$mSubKey] = $mVal;
                }
            }
        }   
    }

    return $aReturn;
}

$newArray = merge_arrays($arrayAAA, $arrayBBB, $arrayCCC);
Bryan B.
  • 897
  • 8
  • 8