Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two arrays by index

Okay, if feel like this should be really simple and accomplished by a function like array_merge() or array_merge_recursive, but I can't quite figure it out. I have two simple arrays structured like the (simplified) example below. I simply want to merge them into one array based on their index.

$array 1:

Array ( 
  [0] => Array ( 
        [ID] => 201 
        [latLng] => 45.5234515, -122.6762071 
  )  
  [1] => Array ( 
        [ID] => 199 
        [latLng] => 37.7931446, -122.39466520000002 
  )
) 

et cetera…

$array2 :

Array ( 
  [0] => Array ( 
        [distance] => 1000 
        [time] => 10 
  )  
  [1] => Array ( 
        [distance] => 1500 
        [time] => 15 
  )
) 

$desiredResult :

Array ( 
  [0] => Array ( 
        [ID] => 201 
        [latLng] => 45.5234515, -122.6762071 
        [distance] => 1000 
        [time] => 10 
 )  
  [1] => Array ( 
        [ID] => 199 
        [latLng] => 37.7931446, -122.39466520000002 
        [distance] => 1500 
        [time] => 15 
 )
) 

When I try to merge these using merge functions, I can only get this:

$unDesiredResult:

Array ( 
  [0] => Array ( 
        [ID] => 201 
        [latLng] => 45.5234515, -122.6762071 
  )  
  [1] => Array ( 
        [ID] => 199 
        [latLng] => 37.7931446, -122.39466520000002 
  )
  [2] => Array ( 
        [distance] => 1000 
        [time] => 10 
  )  
  [3] => Array ( 
        [distance] => 1500 
        [time] => 15 
  )
) 

Do I need to loop through to push the second set into the first, or can this be done with an existing function?

like image 758
Kerri Avatar asked Mar 02 '12 23:03

Kerri


2 Answers

I don't think there is a function to do this for you, you're gonna have to loop.

$result = array();
foreach($array1 as $key=>$val){ // Loop though one array
    $val2 = $array2[$key]; // Get the values from the other array
    $result[$key] = $val + $val2; // combine 'em
}

Or you can push the data into $array1, so you need to make a 3rd array:

foreach($array1 as $key=>&$val){ // Loop though one array
    $val2 = $array2[$key]; // Get the values from the other array
    $val += $val2; // combine 'em
}
like image 180
Rocket Hazmat Avatar answered Sep 22 '22 20:09

Rocket Hazmat


You'll need to use a loop. Try creating a function:

function addArray( array &$output, array $input ) {
    foreach( $input as $key => $value ) {
        if( is_array( $value ) ) {
            if( !isset( $output[$key] ) )
                $output[$key] = array( );
            addArray( $output[$key], $value );
        } else {
            $output[$key] = $value;
        }
    }
}

Then:

$combinedArray = array( );
addArray( $combinedArray, $array1 );
addArray( $combinedArray, $array2 );
like image 44
kitti Avatar answered Sep 23 '22 20:09

kitti