从数据表中检索元素并求和相同的元素

时间:2018-12-14 13:19:29

标签: php database woocommerce

我有woocommerce的“订单”表。 我通过 GET 请求过滤并按状态对元素进行了排序。 结果将复制到 JSON 文件。

因此,现在,我想查找具有相同“ product_id”及其值的元素,并将其汇总以显示在屏幕中,以便进行打印。

例如:

“ product_id”:45329,                 “ variation_id”:0,                 “数量”:1

“ product_id”:48911,                 “ variation_id”:0,                 “数量”:1,

“ product_id”:45329,                 “ variation_id”:0,                 “数量”:1

我要实现的输出是:

45329数量2
48911数量1

谢谢!

1 个答案:

答案 0 :(得分:0)

使用json_decode()解码JSON并进行计算。下一个示例使用简化的JSON数据,我认为该数据与WooCommerce的格式匹配(我猜这种格式是来自列表订单GET请求):

<?php
# JSON
$json = '
[
  {
    "id": 727,
    "line_items": [
      {
        "id": 315,
        "name": "Woo Single #1",
        "product_id": 93,
        "variation_id": 0,
        "quantity": 2,
        "tax_class": "",
        "subtotal": "6.00",
        "subtotal_tax": "0.45",
        "total": "6.00",
        "total_tax": "0.45",
        "taxes": [
          {
            "id": 75,
            "total": "0.45",
            "subtotal": "0.45"
          }
        ],
        "meta_data": [],
        "sku": "",
        "price": 3
      },
      {
        "id": 316,
        "name": "Ship Your Idea &ndash; Color: Black, Size: M Test",
        "product_id": 22,
        "variation_id": 23,
        "quantity": 1,
        "tax_class": "",
        "subtotal": "12.00",
        "subtotal_tax": "0.90",
        "total": "12.00",
        "total_tax": "0.90",
        "taxes": [
          {
            "id": 75,
            "total": "0.9",
            "subtotal": "0.9"
          }
        ],
        "meta_data": [
          {
            "id": 2095,
            "key": "pa_color",
            "value": "black"
          },
          {
            "id": 2096,
            "key": "size",
            "value": "M Test"
          }
        ],
        "sku": "Bar3",
        "price": 12
      }
    ]
  }
]';
$input = json_decode($json, true);

# Sum
$output = array();
foreach ($input as $order) {
    foreach ($order["line_items"] as $item) {
        $product_id = $item['product_id'];
        $quantity   = $item['quantity'];
        if (!array_key_exists($product_id, $output)) {
            $output[$product_id] = 0;
        }   
        $output[$product_id] += $quantity;
    }   
}

#Output
foreach ($output as $key => $value) {
    echo $key.' quantity '.$value.'<br>';
}   
?>

输出:

93 quantity 2
22 quantity 1