亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

顯示兩個價目表之間的差異

顯示兩個價目表之間的差異

PHP
青春有我 2023-06-24 15:55:59
我有產品價格的歷史列表(按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;?>我可以在表中看到真實的輸出,但我需要在第三列中顯示兩個價格之間的差異,如下圖所示:我如何顯示列表中兩個價格之間的差異?!
查看完整描述

2 回答

?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

您只需將當前價格屬性與數組中前一個對象的價格進行比較?


像這樣的東西應該有效:


<?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;?>


查看完整回答
反對 回復 2023-06-24
?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

如果您運行的是 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

這會向結果集中再添加一列,其中包含同一產品的當前價格與之前價格之間的差異。


查看完整回答
反對 回復 2023-06-24
  • 2 回答
  • 0 關注
  • 170 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號