KaekeaSchmear
KaekeaSchmear

Reputation: 1578

Merge PHP Associative Array

I have multiple arrays and i'm trying to merge them. Imagine the following code;

$arr1[ 'a' ] = array( 'a', 'b', 'c' );
$arr2[ 'a' ] = array( 'd', 'e', 'f' );
$arr3[ 'a' ] = array( 'g', 'h', 'i' );

$arr1[ 'b' ] = array( 'a', 'b', 'c' );
$arr2[ 'b' ] = array( 'd', 'e', 'f' );
$arr3[ 'b' ] = array( 'g', 'h', 'i' );

$buf = array_merge( $arr1, $arr2, $arr3 );
print_r( $buf );

The result i'm expecting is;

Array
(
  [a] => Array
    (
      [ 0 ] => a
      [ 1 ] => b
      [ 2 ] => c
      [ 3 ] => d
      [ 4 ] => e
      [ 5 ] => f
      [ 6 ] => g
      [ 7 ] => h
      [ 8 ] => i
    )

  [b] => Array
    (
      [ 0 ] => a
      [ 1 ] => b
      [ 2 ] => c
      [ 3 ] => d
      [ 4 ] => e
      [ 5 ] => f
      [ 6 ] => g
      [ 7 ] => h
      [ 8 ] => i
    )
)

I tried using array_merge( ) and array_combine( ) without success. Hope any one can help.

Upvotes: 1

Views: 96

Answers (4)

Algobasket
Algobasket

Reputation: 13

$arr1[ 'a' ] = array( 'a', 'b', 'c' );

$arr2[ 'a' ] = array( 'd', 'e', 'f' );

$arr3[ 'a' ] = array( 'g', 'h', 'i' );

$arr1[ 'b' ] = array( 'a', 'b', 'c' );

$arr2[ 'b' ] = array( 'd', 'e', 'f' );

$arr3[ 'b' ] = array( 'g', 'h', 'i' );

$array = array(

'a' => array_merge($arr1['a'], $arr2['a'], $arr3['a']),
'b' => array_merge($arr1['b'], $arr2['b'], $arr3['b'])

);

print_r($array);

Upvotes: 0

scrowler
scrowler

Reputation: 24406

array_merge() only looks one level deep into arrays. You should use array_merge_recursive() for this:

$buf = array_merge_recursive( $arr1, $arr2, $arr3 );

Upvotes: 1

Marin Atanasov
Marin Atanasov

Reputation: 3316

Use:

$buf = array_merge_recursive($arr1, $arr2, $arr3);

Upvotes: 4

mpgn
mpgn

Reputation: 7251

Something like this :

<?php
$arr1[ 'a' ] = array( 'a', 'b', 'c' );
$arr2[ 'a' ] = array( 'd', 'e', 'f' );
$arr3[ 'a' ] = array( 'g', 'h', 'i' );

$arr1[ 'b' ] = array( 'a', 'b', 'c' );
$arr2[ 'b' ] = array( 'd', 'e', 'f' );
$arr3[ 'b' ] = array( 'g', 'h', 'i' );

$array = [
    'a' => array_merge($arr1['a'], $arr2['a'], $arr3['a']),
    'b' => array_merge($arr1['b'], $arr2['b'], $arr3['b'])
];

var_dump($array);

Upvotes: 2

Related Questions