Reputation: 2381
I have 2 separate multidimensional arrays that have the same structure. Example:
Array
(
[0] => Array
(
[uploadData] => 1234 Main St
)
[1] => Array
(
[uploadData] => 5678 Elm St
)
[2] => Array
(
[uploadData] => 9879 New St
)
[3] => Array
(
[uploadData] => 9876 Shady Lane
)
)
Array
(
[0] => Array
(
[uploadData] => Orlando
)
[1] => Array
(
[uploadData] => Tampa
)
[2] => Array
(
[uploadData] => Miami
)
[3] => Array
(
[uploadData] => West Palm Beach
)
)
I just need to get them into 1 new array that looks like this:
Array
(
[0] => Array
(
[uploadData] => 1234 Main St Orlando
)
[1] => Array
(
[uploadData] => 5678 Elm St Tampa
)
[2] => Array
(
[uploadData] => 9879 New St Miami
)
[3] => Array
(
[uploadData] => 9876 Shady Lane West Palm Beach
)
)
I've been trying to use array_merge
but I cannot get it to work.
Upvotes: 1
Views: 848
Reputation: 48100
Because the two arrays have the same size and there are no associative first level keys to preserve, they can be mapped together with array_map()
and concatenated.
Code: (Demo)
$streets = [
['uploadData' => '1234 Main St'],
['uploadData' => '5678 Elm St'],
['uploadData' => '9879 New St'],
['uploadData' => '9876 Shady Lane'],
];
$cities = [
['uploadData' => 'Orlando'],
['uploadData' => 'Tampa'],
['uploadData' => 'Miami'],
['uploadData' => 'West Palm Beach'],
];
var_export(
array_map(
fn($s, $c) => ['uploadData' => "{$s['uploadData']} {$c['uploadData']}"],
$streets,
$cities
)
);
Upvotes: 0
Reputation: 198237
Fetch from both arrays until everything is gone:
$final = [];
$key = 'uploadData';
while ($array1 && $array2)
{
$final[][$key] = array_shift($array1)[$key] . ' ' . array_shift($array2)[$key];
}
See array_shift
and converting to booleans.
Upvotes: 1
Reputation: 29492
Simple, recursive, key-independent solution:
function array_concat_recursive($array1, $array2){
$result = array();
foreach($array1 as $key => $value){
if(isset($array2[$key])){
if(is_array($value)){
$result[$key] = array_concat_recursive($value, $array2[$key]);
}else{
$result[$key] = $value . ' ' . $array2[$key];
}
}
}
return $result;
}
Upvotes: 3
Reputation: 26180
Assuming that:
$address
$city
EDIT:
Great catch by @dev-null-dweller - edited to catch full depth of arrays.
NOTE
Example code in question does not have quotes around uploadData key, so that is replicated here:
The following will do what you want:
foreach($address as $key=>$value) {
$newarray = array(
'uploadData'=>$value['uploadData'] . ' ' . $city[$key]['uploadData'];
);
}
The $newarray
will contain an array structured per your request.
Upvotes: 2