Skip to content
Advertisement

show difference between of two price list

I have history list of product price(order by created_at) like this:

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
        )

)

Now for show data in table I listed price using foreach method like this:

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

I can see true output in table but I need to show difference between of two price in the third column like this picture:

enter image description here

how do can i show difference between of two price in my list?!

Advertisement

Answer

You just need to compare the current price property to the price from the previous object in the array?

Something like this should work:

<?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;?>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement