我正在尝试从我的数据库中提取项目,并将它们转换为"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循环来实现。
任何帮助都将不胜感激。
发布于 2019-07-30 19:25:12
例如,您可以将类型转换对象用于如下所示的数组:
protected function setCartItems($items)
{
return (new Collection($items))->map(function ($item, $num) {
$itemArray = (array) $item;
return [
'L_PAYMENTREQUEST_0_NAME'.$num => $itemArray ['name'],
'L_PAYMENTREQUEST_0_AMT'.$num => $itemArray ['price'],
'L_PAYMENTREQUEST_0_DESC'.$num => isset($itemArray ['desc']) ? $itemArray ['desc'] : null,
'L_PAYMENTREQUEST_0_QTY'.$num => isset($itemArray ['qty']) ? $itemArray ['qty'] : 1,
];
})->flatMap(function ($value) {
return $value;
});https://stackoverflow.com/questions/57263406
复制相似问题