显示两个价目表之间的差异

我有产品价格的历史列表(按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;?>

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

http://img1.mukewang.com/6496a1aa0001a36806520190.jpg

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



青春有我
浏览 121回答 2
2回答

ITMISS

您只需将当前价格属性与数组中前一个对象的价格进行比较?像这样的东西应该有效:<?php foreach($product_prices_list as $key => $product_price_list):?>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <td><?= esc($product_price_list->created_at);?></td>&nbsp; &nbsp; &nbsp; &nbsp; <td class="text-center"><?= esc(number_format($product_price_list->price));?></td>&nbsp; &nbsp; &nbsp; &nbsp; <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&nbsp; &nbsp; </tr><?php endforeach;?>

慕田峪4524236

如果您运行的是 MySQL 8.0,则可以使用窗口函数直接在数据库中计算此信息:select&nbsp; &nbsp; t.*,&nbsp; &nbsp; price&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; - lag(price, 1, price) over(partition by product_id order by created_at)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; as price_difffrom mytable t这会向结果集中再添加一列,其中包含同一产品的当前价格与之前价格之间的差异。
打开App,查看更多内容
随时随地看视频慕课网APP