Is there a PHP function to combine the results of 2 arrays based off of keys?
If I have the following arrays
arry1 = array(
101 => array(
'title1' => 'data',
'title2' => 'data',
'title3' => 'data'
),
102 => array(
'title1' => 'data',
'title2' => 'data',
'title3' => 'data'
),
.
.
.
);
arry2 = array(
101 => array(
'title4' => 'data',
'title5' => 'data',
'title6' => 'data'
),
102 => array(
'title4' => 'data',
'title5' => 'data',
'title6' => 'data'
),
.
.
.
);
and I want to change them into
arry3 = array(
101 => array(
'title1' => 'data',
'title2' => 'data',
开发者_开发问答 'title3' => 'data',
'title4' => 'data',
'title5' => 'data',
'title6' => 'data'
),
102 => array(
'title1' => 'data',
'title2' => 'data',
'title3' => 'data',
'title4' => 'data',
'title5' => 'data',
'title6' => 'data'
),
.
.
.
);
Is there a simple function from php arrays to do this? If not, what do you believe would be the most efficient way to program this?
Thanks for any help,
MetropolisEDITED
Sorry I updated the arrays to be the way they actually should be....array_merge_recursive gives me the following,arry3 = array(
0 => array(
'title1' => 'data',
'title2' => 'data',
'title3' => 'data'
),
1 => array(
'title4' => 'data',
'title5' => 'data',
'title6' => 'data'
),
.
.
.
);
I need the 101, and 102 to stick, and I need the data to all be in the same lower level array....
I assume you want to add the latter array to the first. Therefore, use this:
array_merge_recursive(array1, array2);
... and it'll do exactly what you want.
EDIT:
As it seems, that my above solution is not entirely correct, use this:
<?
function array_merge_subarrays(array $array1, array $array2) {
$resultArray = array();
// The foreach instead of a plain for is to keep the specific values of the keys
foreach ($array1 as $key => $subarray) {
$resultArray[$key] = array_merge($subarray, $array2[$key]);
}
return $resultArray;
}
$arr1 = array(
101 => array(
'title1' => 'data',
'title2' => 'data',
'title3' => 'data'
),
102 => array(
'title1' => 'data',
'title2' => 'data',
'title3' => 'data'
)
);
$arr2 = array(
101 => array(
'title4' => 'data',
'title5' => 'data',
'title6' => 'data'
),
102 => array(
'title4' => 'data',
'title5' => 'data',
'title6' => 'data'
)
);
print_r(array_merge_subarrays($arr1, $arr2));
/*
OUTPUTS:
Array (
[101] => Array (
[title1] => data
[title2] => data
[title3] => data
[title4] => data
[title5] => data
[title6] => data
)
[102] => Array (
[title1] => data
[title2] => data
[title3] => data
[title4] => data
[title5] => data
[title6] => data
)
)
*/
?>
精彩评论