我需要在json中提供以下响应:
$output = array(
'storeCode' => '123456',
'firstName' => $fname,
'lastName' => $lname,
'dateOfBirth' => '1983-04-01',
'mobilePhone' => $mobile,
'email' => $email,
'address' => array(
'street' => $address1,
'suiteApartment' => $address2,
'city' => $city,
'state' => $state,
'zipCode'=> $zip
),
'products' => $orderitems,
'redirectUrl' => $cburl,
'referenceNumber' => $order_id
);
尝试以下操作时,我只能获得$orderitems
的第一个实例:
$order = wc_get_order($order_id);
// Get the order ID
$order_id = $order->get_id();
// Initialising
$items = $order->get_items();
$count = 0;
// Loop through Order items
foreach ($order->get_items() as $item_key => $item ):
$product = $item->get_product(); // Get the WC_Product object
$product_id = $item->get_product_id(); // the Product id
$variation_id = $item->get_variation_id(); // the Variation id
$item_type = $item->get_type(); // Type of the order item ("line_item")
$item_name = $item->get_name(); // Name of the product
$quantity = $item->get_quantity();
$tax_class = $item->get_tax_class();
$line_subtotal = $item->get_subtotal(); // Line subtotal (non discounted)
$line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
$line_total = $item->get_total(); // Line total (discounted)
$line_total_tax = $item->get_total_tax(); // Line total tax (discounted)
$orderitems = array(
'id' => $product_id,
'description' => $item_name,
'quantity' => $quantity,
'value' => $line_subtotal,
'salesTax' => $line_subtotal_tax
);
$count++;
endforeach;
为什么在回显变量时为什么只得到数组中的第一项?
您的代码中有一些小错误。尝试以下操作,您将在变量中获取将用于'products'
参数的所有订单商品的特定数据:
$order_id = $order->get_id(); // Get the order ID
$order_items = $order->get_items(); // Get order items array of objects
$items_count = count($items); // Get order items count
$items_data = []; // Initializing
// Loop through order items
foreach ( $order_items as $item_id => $item ) {
$variation_id = $item->get_variation_id();
$product_id = $variation_id > 0 ? $variation_id : $item->get_product_id();
// Set specific data for each item in the array
$items_data[] = array(
'id' => $product_id,
'description' => $item->get_name(),
'quantity' => $item->get_quantity(),
'value' => $item->get_subtotal(),
'salesTax' => $item->get_subtotal_tax(),
);
}
然后将用于:
$output = array(
'storeCode' => '123456',
'firstName' => $fname,
'lastName' => $lname,
'dateOfBirth' => '1983-04-01',
'mobilePhone' => $mobile,
'email' => $email,
'address' => array(
'street' => $address1,
'suiteApartment' => $address2,
'city' => $city,
'state' => $state,
'zipCode' => $zip
),
'products' => $items_data, // <=== HERE
'redirectUrl' => $cburl,
'referenceNumber' => $order_id
);
它应该按预期工作。
相关: