如何“临时”存储已解码JSON表中的某些值?

时间:2019-01-04 14:22:24

标签: php temporary

我正在构造一个函数,该函数使用API​​调用db并返回JSON数据。 json包含命令,我已经在php数组中对其进行了解码。每个订单都具有“ product_id”和“ quantity”之类的属性。我想将“ quantity”属性临时存储在某个地方,因为我需要对所有具有相同product_id的产品求和。有什么建议怎么做吗?

2 个答案:

答案 0 :(得分:1)

我有点着急,但是想看看我能不能帮到你。

$quantities = [];

//Loop through all the orders
foreach ($orders as $order) {
    //Loop through the orderrows
    foreach ($order->getOrderRows() as $orderRow) {
        if (array_key_exists($orderRow->getProductName(), $quantities)) {
            //The product is already in the quantities array, so the quantity of this orderrow is added to the total
            $quantities[$orderRow->getProductName()] =
                ($quantities[$orderRow->getProductName()] + (int) $orderRow->getItemQuantity());
        } else {
            //If this is the first time the product is encountered add the product and its quantity to the quantities array
            $quantities[$orderRow->getProductName()] = (int) $orderRow->getItemQuantity();
        }
    }
}

这将产生以下结果,向您显示产品名称及其数量:

$quantities = [
    'foo' => 12,
    'bar' => 3,
];

答案 1 :(得分:-1)

您可以使用会话变量来存储这些值。