Laravel:如何将键和值添加到Collection或数组中

问题描述 投票:0回答:1

我从数据库获得一个集合,可以使用toarray()更改类型,但是我不怎么向集合或数组中添加键和值

这是我的收藏

Collection {#225 ▼
  #items: array:1 [▼
    0 => {#222 ▼
      +"product_id": 48
      +"product_name": "xxxxxxx"
      +"product_number": 400
      +"product_price": 300
      +"product_describe": "qqqqqqqqqq"
      +"product_status_id": 1
      +"product_category_id": 1
      +"product_buy_price": 200
      +"created_at": null
      +"updated_at": null
    }
  ]
}

这是我的数组

array:1 [▼
  0 => {#222 ▼
    +"product_id": 48
    +"product_name": "xxxxxxx"
    +"product_number": 400
    +"product_price": 300
    +"product_describe": "qqqqqqqqqq"
    +"product_status_id": 1
    +"product_category_id": 1
    +"product_buy_price": 200
    +"created_at": null
    +"updated_at": null
  }
]

我想添加到数组的键和值。

"buynumber" => "$buynumber"

我尝试使用合并。Controller.php

        $buynumber = Input::get('buynumber');
        $product_id = Input::get('product_id');
        $product = DB::table('product')
                        ->where('product_id', $product_id)
                        ->get();

        $product_array = $product->toArray();
        $buy_number = array('buynumber' => $buynumber);
        $merge = array_merge($product_array, $buy_number);
        return  View('shop/cart')
                    ->with('merge',$merge);

不是我想要的。

合并结果

array:2 [▼
  0 => {#222 ▼
    +"product_id": 48
    +"product_name": "同榮辣味紅燒鰻"
    +"product_number": 400
    +"product_price": 300
    +"product_describe": "採用新鮮海鰻製成,當作配菜開胃爽口"
    +"product_status_id": 1
    +"product_category_id": 1
    +"product_buy_price": 200
    +"created_at": null
    +"updated_at": null
  }
  "buynumber" => "5"
]

如何获得一个数组而不是两个数组?

arrays laravel collections
1个回答
0
投票

尝试对其进行映射,并使用Array Add Helper

use Illuminate\Support\Arr;
...

$product->map(function($arr) use($array, $buynumber) {
   Arr::add($arr, 'buynumber', $buynumber);
});
© www.soinside.com 2019 - 2024. All rights reserved.