Reputation: 53
Supposing I've this array:
Array
(
[country] => Array
(
[0] => France
[1] => Canada
)
[capital] => Array
(
[0] => Paris
[1] => Ottawa
)
[other] => value
)
Is it possible to merge the country
and capital
arrays ?
The desired output is the following:
Array
(
[countries] => Array
(
Array
(
[country] => France
[capital] => Paris
)
Array
(
[country] => Canada
[capital] => Ottawa
)
)
[other] => value
)
What I tried:
$result = array();
foreach($arr as $key=>$array) {
$result[$key] = array_merge($array, $arr2[$key]);
}
Upvotes: 1
Views: 49
Reputation: 11642
If you have known field to modify use:
$arr = ["country" => ["France", "Canada"], "capital" => ["Paris", "Ottawa"], "other" => "value"];
$keys = ["country", "capital"];
foreach($arr as $k => $v) {
if (in_array($k, $keys)) {
$slice[] = $v; // get the array which need to be merge
unset($arr[$k]); // remove him from the original array
}
}
$arr["countries"] = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, array_map(null, ...$slice));
And now $arr
is set.
Notice the use of ...
operator to explode the $slice
array and the array_map
with null
which combine according to int keys.
This is the most generic way because if you want to change the field to merge you only need to do so in 1 place...
Upvotes: 1
Reputation: 71
Try to use below code it will works 100%
thank you.
<?php
$arr = [
"country"=>["France","Canada"],
"capital"=>["Paris","Ottawa"],
"other"=>[]
];
$result = [
"countries"=>[]
];
for($i=0;$i<count($arr["country"]);$i++){
$data = [
"country"=>$arr["country"][$i],
"capital"=>$arr["capital"][$i]
];
array_push($result["countries"],$data);
}
echo "<pre>";
print_r($result);
echo "</pre>";
Upvotes: 0
Reputation: 1175
If countries
-> capitals
keys and length are the same and you need only those values to be combined you can simply increment through one of arrays. For example:
$result = ['countries' => [], 'other' => $arr['other']];
for ($i = 0; $i < count($arr['country']); $i++) {
$result['countries'][] = [
'country' => $arr['country'][$i],
'capital' => $arr['capital'][$i]
];
}
Upvotes: 1