1

I think this is a very simple question, but can't figure out how to this. I've these two arrays:

(
    [0] => Array
    (
        [accordion_title] => [accordion-title]Title 1[/accordion-title]
    )
    [1] => Array
    (
        [accordion_title] => [accordion-title]Title 2[/accordion-title]
    )
)

(
    [0] => Array
    (
        [accordion_content] => [accordion-content]Content 1[/accordion-content]
    )
    [1] => Array
    (
        [accordion_content] => [accordion-content]Content 2[/accordion-content]
    )
)

How can I combine/merge them that they look like this?

(
    [0] => Array
    (
        [accordion_title] => [accordion-title]Title 1[/accordion-title]
        [accordion_content] => [accordion-content]Content 1[/accordion-content]
    )
    [1] => Array
    (
        [accordion_title] => [accordion-title]Title 2[/accordion-title]
        [accordion_content] => [accordion-content]Content 2[/accordion-content]
    )
)

Thanks for your help.

4 Answers4

2

You can try in this way:

$array1 = array( array('accordion_title'=>'Title 1'),array('accordion_title'=>'Title 2') );
$array2 = array( array('accordion_content'=>'Content 1'),array('accordion_content'=>'Content 2') );

$array3 = array();
foreach( $array1 as $key => $array )
{
    $array3[] = array( key($array) => current($array), key($array2[$key]) => current($array2[$key]) );
}

print_r( $array3 );

This is the output:

Array
(
    [0] => Array
        (
            [accordion_title] => Title 1
            [accordion_content] => Content 1
        )

    [1] => Array
        (
            [accordion_title] => Title 2
            [accordion_content] => Content 2
        )

)

Updated:

With this function you can combine infinite arrays (not only two), even if they have different sizes:

/*   Groups passed arrays in an array of associative arrays with same keys and values
 *
 *   @example          $array1 = array( array('a'=>'val1'),array('a'=>'val2') );
 *                     $array2 = array( array('b'=>'val3'),array('b'=>'val4') );
 *                     $array3 = array( array('c'=>'val5'),array(),array('c'=>'val6') );
 *                     multiArrayCombine( $array1, $array2, $array3 );
 *                     return: array
 *                     (
 *                        0 => array('a'=>'val1','b'=>'val3','c'=>'val5'),
 *                        1 => array('a'=>'val2','b'=>'val4'),
 *                        2 => array('c'=>'val6')
 *                     )
 *                     
 *   @param   array    $array1[, $array2[, $array3...]]
 *
 *   @option  const    T_OBJECT_CAST cast returned assoc arrays as stdObject
 *
 *   @return  array
 */
function multiArrayCombine()
{
    /* Get all passed parameters and T_OBJECT_CAST option: */
    $args     = func_get_args();
    $asObject = ( T_OBJECT_CAST == end($args) );
    if( $asObject ) array_pop( $args );

    $retval = array();          # Init array to be returned
    
    /* Retrieve highest passed arrays key: */
    $max = 0;
    foreach( $args as $array ) $max = max( $max, max( array_keys($array) ) );

    /* Loop for each arrays key: */
    for( $i=0; $i<=$max; $i++ )
    {
        /* Init associative array to add:  */
        $add = array();
        
        /* Process actual key ($i) of each passed array:  */
        foreach( $args as $array )
        {
            /* If the key ($i) exists, add  each passed array:  */
            if( isset($array[$i]) AND is_array($array[$i]) )
            {
                foreach( $array[$i] as $key => $val )
                { $add[$key] = $val; }
            }
        }
        
        /* Add the obtained associative array to return array */
        if( $asObject ) $retval[] = (object) $add;
        else            $retval[] = $add;
    }
    
    return $retval;
}

So, with the following code (three arrays):

$array1 = array( array('accordion_title'=>'Title 1'),array('accordion_title'=>'Title 2') );
$array2 = array( array('accordion_content'=>'Content 1'),array('accordion_content'=>'Content 2') );
$array3 = array( array('accordion_date'=>'Date 1'),array(),array('accordion_date'=>'Date 3') );

print_r( multiArrayCombine( $array1, $array2, $array3 ) );

the output is:

Array
(
    [0] => Array
        (
            [accordion_title] => Title 1
            [accordion_content] => Content 1
            [accordion_date] => Date 1
        )

    [1] => Array
        (
            [accordion_title] => Title 2
            [accordion_content] => Content 2
        )

    [2] => Array
        (
            [accordion_date] => Date 3
        )
)

3v4l.org demo

Updated 2:

  1. Now the function return all passed values of each rows, not only the first;
  2. Added option T_OBJECT_CAST: passing constant T_OBJECT_CAST after the list of arrays, rows of returned array as formatted as stdObjects instead of arrays.

Explanation:

To allow not predetermined arguments, I don't format function as `multiArrayCombine( $arg1, $arg2, ... )`, I use instead the [`func_get_args()`](http://php.net/manual/en/function.func-get-args.php) function, that "allow user-defined functions to accept variable-length argument lists".

First of all (in the latest update), I check if the last argument is the predefined constant T_OBJECT_CAST: if it is, I set $asObject to True, then I pop-it off the end of arguments array; now in the $args variable I have an array with each passed arrays.

Next step: I retrieve the max key value of all passed arrays; i choose this way instead of more comfortable foreach( $array1 as $row ) to avoid to omit values if one of the other arrays have more rows than the first. Eventually not numeric keys are omitted.

Then, the main loop: I process each row of originals arrays and I add their keys and values to row that will added to returned array. If there are duplicated keys, only the last is returned.

After processing each array, i add the obtained row (converted to object if this option is passed) to returning array.

That's all!


Globish here, i'm sorry

fusion3k
  • 11,568
  • 4
  • 25
  • 47
  • +1 for using a function! Seems to work perfect. Could you pls explain the function in general? There are some parts i don't undertand like the foreach(func_get_args ... line – Tobias Malikowski Jan 28 '16 at 07:55
  • @TobiasMalikowski added explanation and improved function with new feature and option. Thank you for your appreciation. Sorry for bad english – fusion3k Jan 28 '16 at 10:31
  • Thank you very much, you made my day! Also thanks for the explanation. I'm sure that will help other people who may find this usefull. – Tobias Malikowski Jan 28 '16 at 12:02
  • @fusion3k please help to consolidate Stack Overflow content for researchers by posting your unique advice on canonical pages instead of improving answers on signpost pages. I believe if you add your advice to the dupe target, this redundant page can be safely purged. – mickmackusa Feb 21 '23 at 05:27
1

Something like this should work:

$merged = [];
$array1 = [ ... ];
$array2 = [ ... ];
foreach ($array1 as $key => $value) {
    $merged[$key][] = $value;
}
foreach ($array2 as $key => $value) {
    $merged[$key][] = $value;
}

I hope what I've done here makes sense.

Andrea
  • 19,134
  • 4
  • 43
  • 65
0

Simply make iterated array_merge() calls via array_map() and just pass in all of the arrays that should be merged.

Code: (Demo)

$array1 = [
    ['accordion_title' => '[accordion-title]Title 1[/accordion-title]'],
    ['accordion_title' => '[accordion-title]Title 2[/accordion-title]']
];
$array2 = [
    ['accordion_content' => '[accordion-content]Content 1[/accordion-content]'],
    ['accordion_content' => '[accordion-content]Content 2[/accordion-content]']
];

var_export(array_map('array_merge', $array1, $array2));

Output:

array (
  0 => 
  array (
    'accordion_title' => '[accordion-title]Title 1[/accordion-title]',
    'accordion_content' => '[accordion-content]Content 1[/accordion-content]',
  ),
  1 => 
  array (
    'accordion_title' => '[accordion-title]Title 2[/accordion-title]',
    'accordion_content' => '[accordion-content]Content 2[/accordion-content]',
  ),
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1

Maybe use the php function array array_merge($array1 ,$array2)

http://php.net/manual/fr/function.array-merge.php