如何在多维数组的末尾添加键值对


How to add a key value pair at the end of a multidimensional array?

我正在为一个项目处理数组,我想知道如何在数组末尾添加键值对。以下是要素:

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)
);

使用循环可以简单地完成:

$result = [];
foreach ($cart as $attributes) {
    foreach ($items as $item) {
        if ($item['id'] == $attributes['id']) {
            $result[] = $item + $attributes;
        }
    }
}
var_dump($result);

在序列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);