1

I've been searching through SO and come across a couple solutions that all feel like hacks for getting around the default array_merge_recursive behavior on numeric keys. For instance, I've read that you can add an underscore to the beginning, changing your number to a string.

Anyway, here's my data set and intended outcome...

array ( "Name1", "Name2", "Name3" );
array ( "Data1", "Data2", "Data3" );
array ( "Price1", "Price2", "Price3" );

Intended outcome:

array ( 1 => array ( "Name1", "Data1", "Price1" ), 2 => array ( "Name2", "Data2", "Price2" ), 3 => array ( "Name3", "Data3", "Price3" );

I'm sure you're aware of how array_merge_recursive normally operates with numeric keys... Here's my current merged results.

array ( "Name1", "Name2", "Name3", "Data1", "Data2", "Data3", "Price1", "Price2", "Price3");

Is there a proper method for this? What are the pros and cons to individual methods, like adding an underscore to create a string key?

2 Answers 2

4

A simple workaround would be a completely different approach, like:

$merged = array_map(function () { return func_get_args(); }, $array1, $array2, $array3);
Sign up to request clarification or add additional context in comments.

1 Comment

I like that. All the other methods involve creating custom functions and multiple lines of code. This is the sort of solution I was looking for and this works as I hoped for. Thanks!
0
$merge_array = array();
for($i = 0; $i < count($array1); $i++) {
    $row = array();
    $row[] = $array1[$i];
    $row[] = $array2[$i];
    $row[] = $array3[$i];
    $merged_array[] = $row;
}

That should work.

1 Comment

thats kinda booring,though... and its also not recursive.

Your Answer

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