Reputation: 23
I've got these two php arrays I want to merge, one is a multi dimensional array and the needle is a normal single dimensional array :
Array containing ALL possible locations:
Array
(
[Bedfordview] => 0
[Killarney] => 0
[Melrose] => 0
[Midrand] => 0
[Morningside] => 0
)
I want to merge it with the follow multidimentional array:
Array
(
[11] =>
[12] => Array
(
[Bedfordview] => 7
[Melrose] => 2
[Midrand] => 87
[Morningside] => 4
)
[13] => Array
(
[Morningside] => 8
[Killarney] => 1
)
)
I Need the end result to look like this:
Array
(
[11] => Array
(
[Bedfordview] => 0 ==FROM FIRST ARRAY
[Killarney] => 0 ==FROM FIRST ARRAY
[Melrose] => 0 ==FROM FIRST ARRAY
[Midrand] => 0 ==FROM FIRST ARRAY
[Morningside] => 0 ==FROM FIRST ARRAY
)
[12] => Array
(
[Bedfordview] => 7
[Melrose] => 2
[Midrand] => 87
[Morningside] => 4
[Killarney] => 0 ==FROM FIRST ARRAY
)
[13] => Array
(
[Bedfordview] => 0 ==FROM FIRST ARRAY
[Melrose] => 0 ==FROM FIRST ARRAY
[Midrand] => 0 ==FROM FIRST ARRAY
[Morningside] => 8
[Killarney] => 1
)
)
Any ideas?
Upvotes: 2
Views: 56
Reputation: 728
For this, I would use array_merge.
Code
<?php
$locations = array(
'Bedfordview' => 0,
'Killarney' => 0,
'Melrose' => 0,
'Midrand' => 0,
'Morningside' => 0
);
$data = array(
11 => array(),
12 => array(
'Bedfordview' => 7,
'Melrose' => 2,
'Midrand' => 87,
'Morningside' => 4
),
13 => array(
'Morningside' => 8,
'Killarney' => 1
)
);
$result = array();
foreach ($data as $key => $values) {
$result[$key] = array_merge($locations, $values);
}
print_r($result);
Result
Array
(
[11] => Array
(
[Bedfordview] => 0
[Killarney] => 0
[Melrose] => 0
[Midrand] => 0
[Morningside] => 0
)
[12] => Array
(
[Bedfordview] => 7
[Killarney] => 0
[Melrose] => 2
[Midrand] => 87
[Morningside] => 4
)
[13] => Array
(
[Bedfordview] => 0
[Killarney] => 1
[Melrose] => 0
[Midrand] => 0
[Morningside] => 8
)
)
Upvotes: 1
Reputation: 1572
Use PHP function array_merge
http://www.w3schools.com/php/func_array_merge.asp
You can also try it
http://www.w3schools.com/php/showphp.asp?filename=demo_func_array_merge2
Upvotes: 0