2014-06-17 110 views
1

我接到訂單。每個訂單都有一個類型,即'Vanilla'和一個尺寸,即'帶有數量的Mini。如何比較循環中的值?

如果有5個迷你香草我希望它顯示一次不是5次。我也想要數量。

這裏的很多事情,我試圖

$prevSize = null; 
$prevType= null; 

foreach ($orders as $order){ 
echo '<tr>'; 
$new_order = new WC_Order(); 
    $order_items = $new_order->get_items(); 

    foreach ($order_items as $order_item){ 
    $currentSize = $order_item['pa_size']; 
    $currentType = wp_get_post_terms($order_item['product_id'],'pa_ct'); 
    $currentType = $currentType[0]->name; 

    if($prevSize != $currentSize){ 
    echo $currentType . '<br>'; 
    echo $currentSize . '<br>'; 
    } 
    $count += $order_item['qty']; 
    echo $count; 
} 
    $prevSize = $currentSize; 
    $prevType = $currentType;} 
+0

在'$ prevType'之後插入'$ count'並將其賦值爲'0'。連接使用點而不是加號。 '$ count = 0' | '$ count。= $ order_item ['qty']' – kosmos

+0

爲什麼不使用帶有表示產品(「mini_vanilla」)的唯一鍵和表示數量的值的關聯數組?在每次迭代中,將數量添加到數組中,並在退出循環後顯示數組。 – Bogdan

回答

0

我們已經分析了您的查詢,並根據您的需要之一,這裏是我的解決方案:

$order_type = array(); 
foreach ($orders as $order){ 
    echo '<tr>'; 
    $new_order = new WC_Order(); 
    $order_items = $new_order->get_items(); 
    $count = 0; 
    foreach ($order_items as $order_item){ 
    $currentSize = $order_item['pa_size']; 
    $currentType = wp_get_post_terms($order_item['product_id'],'pa_ct'); 
    $currentType = $currentType[0]->name; 
    $temp_order_type = $currentSize.'_'.$currentType; 
    if(!in_array($temp_order_type, $order_type)){ 
     $order_type[] = $temp_order_type; 
     echo $currentType . '<br>'; 
     echo $currentSize . '<br>'; 
    } 
    $count += $order_item['qty']; 
    } 
    echo $count; 
} 

上面的代碼會顯示每個訂單鍵入一次不顯示多次。並顯示每個訂單中訂購的數量。