【问题标题】:Get Specific Data Structure with WooCommerce Order items使用 WooCommerce 订单项获取特定数据结构
【发布时间】:2019-01-22 13:14:56
【问题描述】:

对于下一个订单并且该订单包含 3 个产品,我需要获取格式如下的数据结构:

[items] => Array
(
    [0] => Array
    (
        [sku] => Product 1 sku
        [qty] => Product 1 qty
        [price] => Product 1 price
        [weight] =>
        [discount] =>
        [line_ref] =>
    )

    [1] => Array
    (
        [sku] => Product 2 sku
        [qty] => Product 2 qty
    )

    [2] => Array
    (
        [sku] => Product 3 sku
        [qty] => Product 3 qty
    )

)

这是我的代码:

$order = new WC_Order( $order_id );
// Get the order ID
$order_id = $order->get_id();

// Get data from Items
foreach ( $order->get_items() as $item_key => $item_values ) {  

    $product_id = $item_values->get_product_id(); // the Product id
    $product = $item_values->get_product(); // the WC_Product object
    $item_data = $item_values->get_data();

     $item = array(array(
        'sku'       => $product->get_sku(),
        'qty'       => $item_data['quantity'],
        'price'     => $product->get_price(),
        'weight'    => '',
        'discount'  => '',
        'line_ref'  => ''
        ),
        array(
        'sku'       => $product->get_sku(),
        'qty'       => $item_data['quantity'],
        )
     );

}
print_r($item);

我怎样才能做到这一点?

我正在获取订单中第一个产品的唯一数据。 如果我这样做 print_r($item);在 foreach 循环中,它会根据订单中的产品数量重复整个数据。

【问题讨论】:

    标签: php wordpress woocommerce orders


    【解决方案1】:

    试试下面的

    // Get an instance of the order Object
    $order = wc_get_order( $order_id );
    
    // Get the order ID
    $order_id = $order->get_id();
    
    // Initialising
    $items_data = array(); 
    $count = 0;
    
    // Loop through Order items
    foreach ( $order->get_items() as $item_id => $item ) {  
        $product_id = $item->get_product_id(); // the Product id
        $product    = $item->get_product(); // the WC_Product object
        $item_data  = $item->get_data(); // The line item unprotected data (array)
    
        if( $count === 0 ) {
            $items_data[] = array(
                'sku'       => $product->get_sku(),
                'qty'       => $item->get_quantity(),
                'price'     => $product->get_price(),
                'weight'    => '',
                'discount'  => '',
                'line_ref'  => ''
            );
        } else {
            $items_data[] = array(
                'sku'       => $product->get_sku(),
                'qty'       => $item->get_quantity(),
            );
        }
        $count++;
    }
    $output = array('items' => $items_data );
    
    // Testing output
    print_r($output);
    

    它应该更好地工作。

    【讨论】:

    • 感谢@LoicTheAztec,我得到了我正在寻找的确切解决方案。
    猜你喜欢
    • 2021-03-20
    • 2020-01-25
    • 2018-03-16
    • 1970-01-01
    • 2018-10-26
    • 2019-09-08
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多