Reputation: 53
I am trying to merge two arrays containing a multidimensional array and create a third array in the format below"
Here is the first multidimensional array:
Array
(
[USA1] => Array
(
[0] => NewYork
[1] => MASS
)
[USA2] => Array
(
[0] => NewYork
)
[USA3] => Array
(
[0] => NewYork
)
)
This is my second multidimensional array:
Array
(
[USA1] => Array
(
[NewYork] => Array
(
[0] => Array
(
[0] => Town1
[1] => Town2
)
)
[MASS] => Array
(
[0] => Array
(
[0] => Town3
[1] => Town4
)
)
)
[USA2] => Array
(
[NewYork] => Array
(
[0] => Array
(
[0] => Town1
[1] => Town2
)
)
)
Now i want to make 3rd array which will be merging based on there common key. If the keys are matching then i need to assign one of the values to this array in round robin fashion:
For e.g. If the value is "NewYork" under USA1 key, then i have to assign "Town1" value from another array. As this key is also present under USA2 then i have to assign "Town2" (round robin fashion). If there are more "NewYork" values are present and if have more values like "Town9" then we have to assign that value, if not present then i have to assign "Town1" value back. If the key is present only one time like "MASS" then we need to remove second value which is "Town4" in this case.
Array
(
[USA1] => Array
(
[0] => NewYork => Town1
[1] => Mass => Town3
)
[USA2] => Array
(
[0] => NewYork => Town2
)
[USA3] => Array
(
[0] => NewYork =>Town1
)
)
Note: All the Array output except 3rd one is from print_r command
Greatly appreciate the help. Thank you.
Upvotes: 0
Views: 158
Reputation: 6348
I'm not exactly clear what you're asking for. It's not really a merger because in your final array [USA3] should be empty as there's no matching key in array2. And you're asking for the values to be assigned round-robin, which is not how I expect an array merge to behave.
What I'm assuming you're trying to do is evenly distribute the towns across the cities. Based on that assumption I only used values from USA1 in array two, but this will produce the third array you provided. I've updated the code example to merge the second array.
$map = array();
foreach ($array2 as $usa => $cities)
{
$map = $cities + $map;
}
$towns = array();
foreach($array1 as $usa => $cityArray)
{
while(!empty($cityArray))
{
$city = array_shift( $cityArray );
if(empty($towns[$city]))
$towns[$city] = $map[$city][0];
$array3[ $usa ][] = array( $city => array_shift( $towns[$city] ) );
}
}
This works but if you have different values in $array2['US1'] and $array2['US2'] then you should merge those two arrays before sending it to the code above. Updated code merges the second array properly.
Upvotes: 1