【问题标题】:Laravel 5 array: Cannot use object of type stdClass as arrayLaravel 5 数组:不能使用 stdClass 类型的对象作为数组
【发布时间】: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

标签: php laravel laravel-5


【解决方案1】:

例如,您可以将类型转换对象用于这样的数组:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2021-12-17
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    相关资源
    最近更新 更多