【发布时间】:2019-12-07 08:36:18
【问题描述】:
我正在尝试从我的数据库中获取项目并将它们放入“laravel-paypal”包所需的格式:
$data['items'] = [
[
'name' => 'Product 1',
'price' => 9.99,
'desc' => 'Description for product 1'
'qty' => 1
],
[
'name' => 'Product 2',
'price' => 4.99,
'desc' => 'Description for product 2',
'qty' => 2
]
];
所以我有一个很好的问题:
$order_items = DB::table('order_items')
->where('order_id', $order['id'])
->join('products', 'order_items.product_id', '=', 'products.id')
->selectRaw('products.name, order_items.price + order_items.tax as price, order_items.quantity as qty')
->get()
->toArray();
产量:
array:2 [▼
0 => {#296 ▼
+"name": "fugit"
+"price": 727.82
+"qty": 1
}
1 => {#298 ▼
+"name": "MEMBERSHIP"
+"price": 35.0
+"qty": 1
}
]
但是当我尝试将它放入所需的数组时:
$data = [];
$data['items'] = $order_items;
我收到错误消息:
Symfony\Component\Debug\Exception\FatalThrowableError (E_ERROR) 不能将 stdClass 类型的对象用作数组
详细说明:
protected function setCartItems($items)
{
return (new Collection($items))->map(function ($item, $num) {
return [
'L_PAYMENTREQUEST_0_NAME'.$num => $item['name'],
'L_PAYMENTREQUEST_0_AMT'.$num => $item['price'],
'L_PAYMENTREQUEST_0_DESC'.$num => isset($item['desc']) ? $item['desc'] : null,
'L_PAYMENTREQUEST_0_QTY'.$num => isset($item['qty']) ? $item['qty'] : 1,
];
})->flatMap(function ($value) {
return $value;
});
我已阅读此错误消息的所有解决方案,他们都说我拥有的是对象数组,而不是数组数组,这就是我收到此消息的原因。我知道了。他们都说我必须使用$order_items->price 访问数据。我明白了。
但是我需要该数组格式的数据,并且由于它是一个嵌套数组,我什至无法弄清楚如何使用 foreach 循环来实现。
任何帮助将不胜感激。
【问题讨论】:
-
现在只需在
return [之前写$item = json_decode(json_encode($item),true);即可解决。如果您想选择更强大的解决方案,请阅读有关对象和数组的信息 :) -
只需使用
$item->name。