【问题标题】:show difference between of two price list显示两个价目表之间的差异
【发布时间】:2020-10-12 20:18:00
【问题描述】:

我有这样的产品价格历史列表(按 created_at 排序):

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [product_id] => 49
            [price] => 14520000.0000
            [created_at] => 1592501154
        )

    [1] => stdClass Object
        (
            [id] => 2
            [product_id] => 49
            [price] => 14000000.0000
            [created_at] => 1592587554
        )

    [2] => stdClass Object
        (
            [id] => 4
            [product_id] => 49
            [price] => 14800000.0000
            [created_at] => 1592673954
        )

    [3] => stdClass Object
        (
            [id] => 5
            [product_id] => 49
            [price] => 10000000.0000
            [created_at] => 1592760354
        )

    [4] => stdClass Object
        (
            [id] => 6
            [product_id] => 49
            [price] => 14000000.0000
            [created_at] => 1592846754
        )

    [5] => stdClass Object
        (
            [id] => 7
            [product_id] => 49
            [price] => 14000000.0000
            [created_at] => 1592933154
        )

    [6] => stdClass Object
        (
            [id] => 8
            [product_id] => 49
            [price] => 14000000.0000
            [created_at] => 1593019554
        )

)

现在为了在表格中显示数据,我使用foreach 方法列出价格,如下所示:

   <?php foreach($product_prices_list as $product_price_list):?>
     <tr>
         <td><?= esc($product_price_list->created_at);?></td>
         <td class="text-center"><?= esc(number_format($product_price_list->price));?></td>
         <td class="text-center"></td> //show difference between of two price
     </tr>
   <?php endforeach;?>

我可以在表格中看到真实的输出,但我需要在第三列中显示两个价格之间的差异,如下图所示:

如何在我的列表中显示两个价格之间的差异?!

【问题讨论】:

标签: php mysql date select window-functions


【解决方案1】:

如果您运行的是 MySQL 8.0,您可以使用窗口函数直接在数据库中计算此信息:

select
    t.*,
    price 
        - lag(price, 1, price) over(partition by product_id order by created_at) 
        as price_diff
from mytable t

这会在您的结果集中再增加一列,其中包含同一产品的当前价格与之前价格之间的差异。

【讨论】:

【解决方案2】:

您只需要将当前价格属性与数组中前一个对象的价格进行比较?

这样的事情应该可以工作:

<?php foreach($product_prices_list as $key => $product_price_list):?>
    <tr>
        <td><?= esc($product_price_list->created_at);?></td>
        <td class="text-center"><?= esc(number_format($product_price_list->price));?></td>
        <td class="text-center"><?= (!empty($product_prices_list[$key - 1])) ? $product_prices_list[$key + 1]->price - $product_price_list->price: 0; ?></td> //show difference between of two price
    </tr>
<?php endforeach;?>

【讨论】:

  • 我觉得你应该把$key - 1改成$key + 1
  • @H3llC0d3r 我刚刚修改了答案。看起来记录是从最旧到最新的,所以$key - 1是要与之前的记录进行比较。
猜你喜欢
  • 1970-01-01
  • 2017-11-02
  • 2023-03-26
  • 1970-01-01
  • 2020-04-03
  • 2018-01-06
  • 2010-11-28
  • 1970-01-01
  • 2015-04-06
相关资源
最近更新 更多