我正在为项目工作数组,我想知道如何在数组末尾添加键值对。 所以这里有元素:
1st array
$items = array(
array('id' => '1', 'desc'=>'Canadian-Australian Dictionary', 'price'=>24.95),
array('id' => '2', 'desc'=>'As-new parachute (never opened)', 'price'=> 1000),
array('id'=>'3', 'desc'=>'Songs of the Goldfish (2CD set)', 'price'=> 19.99));
2nd array:
$cart = array(
array('id' => '1','quantity'=>2)
);
所以基本上我想知道的是如何根据id将第一个数组的值添加到第二个数组,以得到像这样的数组。
final array i want to get:
$itemDetail = array(
array('id' => '1', 'desc'=>'Canadian-Australian Dictionary', 'price'=>24.95, 'quantity'=> 1)
);
答案 0 :(得分:1)
你可以用循环来做到这一点:
$result = [];
foreach ($cart as $attributes) {
foreach ($items as $item) {
if ($item['id'] == $attributes['id']) {
$result[] = $item + $attributes;
}
}
}
var_dump($result);
答案 1 :(得分:1)
工作对于两个数组看起来如上所示,序列id以1开始
$items = array(
array('id' => '1', 'desc'=>'Canadian-Australian Dictionary', 'price'=>24.95),
array('id' => '2', 'desc'=>'As-new parachute (never opened)', 'price'=> 1000),
array('id'=>'3', 'desc'=>'Songs of the Goldfish (2CD set)', 'price'=> 19.99));
$cart = array(
array('id' => '1','quantity'=>2)
);
function my_array_merge(&$array1, &$array2) {
$result = Array();
foreach($array1 as $key => &$value) {
$result[$key] = array_merge($value, $array2[$key]);
}
return $result;
}
$array = my_array_merge($items, $cart);
print_r($array);