1

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.

4 Answers 4

4

Use:

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

Sign up to request clarification or add additional context in comments.

Comments

2

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);

1 Comment

I like this solution, but it won't scale at all - you'll need to keep adding levels to your $array each time a key is added, or create a loop to do it. PHP's built in functions will almost always win over custom logic.
1

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

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

Comments

0

$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);

1 Comment

This is essentially the same answer as this one, which was posted 30 minutes ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.