I have two arrays, with the same keys, but there are two different values, they are city and quantity. How can I combine everything into one? i have this
$arr1 = array(
[0] => Array
(
[article] => А6-01-05
[name] => Example
[price] => 9 700
[quantity] => 3
[brand] => Oktan
[code] => УТ-00024246
[city] => Nur-Sultan
)
)
$arr2 = array(
[0] => Array
(
[article] => А6-01-05
[name] => Example
[price] => 9 700
[quantity] => 5
[brand] => Oktan
[code] => УТ-00024246
[city] => Almaty
)
)
i need
$arr = array(
[0] => Array
(
[article] => А6-01-05
[name] => Example
[price] => 9 700
[quantity] => 3
[quantity2] = 5
[brand] => Oktan
[code] => УТ-00024246
[city] => Nur-Sultan
[city2] => Almaty
)
)
CodePudding user response:
I just write a simple code that can merge them as your needs, please take a try this:
<?php
$arr1 = array(
0 => array
(
"article" => "А6-01-05",
"name" => "Example",
"price" => 9700,
"quantity" => 3,
"brand" => "Oktan",
"code" => "УТ-00024246",
"city" => "Nur-Sultan",
)
);
$arr2 = array(
0 => array
(
"article" => "А6-01-05",
"name" => "Example",
"price" => 9700,
"quantity" => 5,
"brand" => "Oktan",
"code" => "УТ-00024246",
"city" => "Almaty"
)
);
$result = [];
foreach ($arr1 as $k => $item) {
$result[$k] = $item;
if (!isset($arr2[$k])) {
continue;
}
foreach ($arr2[$k] as $k2 => $v) {
if (!isset($result[$k][$k2])) {
$result[$k][$k2] = $v;
continue;
}
if ($result[$k][$k2] === $v) {
continue;
}
for ($i = 2; $i < PHP_INT_MAX; $i ) {
if (!isset($result[$k][$k2 . $i])) {
break;
}
}
$result[$k][$k2 . $i] = $v;
}
ksort($result[$k]);
}
var_dump($result);
CodePudding user response:
$arr1 = array(
[
'article' =>'А6-01-05',
'name' =>'Example',
'price' =>'9 700',
'quantity' =>'3',
'brand' =>'Oktan',
'code' =>'УТ-00024246',
'city' =>'Nur-Sultan',
]
);
$arr2 = array(
[
'article' =>'А6-01-05',
'name' =>'Example',
'price' =>'9 700',
'quantity' =>'5',
'brand' =>'Oktan',
'code' =>'УТ-00024246',
'city' =>'Almaty',
]
);
$result = array_map(function($a1, $a2){
$diff = array_diff($a2, $a1);
$dkey = array();
foreach($diff as $dk => $dv){
$dkey[$dk. "2"] = $dv;
}
return array_merge($a1, $dkey);
}, $arr1, $arr2);
print_r($result);
/*
OUTPUT
------
Array
(
[0] => Array
(
[article] => А6-01-05
[name] => Example
[price] => 9 700
[quantity] => 3
[brand] => Oktan
[code] => УТ-00024246
[city] => Nur-Sultan
[quantity2] => 5
[city2] => Almaty
)
)
*/