XF 2.2 Get the latest two values from the database

gaga

Member
Hello, I need some help.
I build the addon that gets the price from API and writes in the database,
database looks like
idcat_idpricecurrencydate
13100USD1647331547
2350USD1647332430

I want to fetch the last two values and compare them.

I use this repo.
PHP:
    public function findPriceFromList($catId, $applyDefaultLimit = true)
    {
        $finder = $this->finder('gaga\Price:Price');

        $finder->where('cat_id', '=', $catId);

        if ($applyDefaultLimit) {
            $finder->limit(2);
        }

        $finder->setDefaultOrder('date', 'DESC');

        return $finder;
    }

In the template, I want to show all prices for each category and % higher or lower price than the previous one.
For e.x in the category with ID 3 listed prices 100 and 50.
after 50 I need to show -50% (calculated from the previous price).

Someone, to help me?

Thanks
 
So let's assume you're looping through your rows. So it would look something like this
PHP:
$prices = array();
foreach($rows as $row){
    $prices[] = $row->price
}

if(count($prices) == 2){
    list($original, $new) = $prices;
 
    $diff = (int) $original - (int) $new;
    $percent = number_format(((int)$new*100)/(int)$original, 2);
    if($diff == 0){
        $change = 0;
    } else if($diff > 0){
        $change = -$percent;
    } else {
        $change = $percent;
    }
} else {
      die('Did not find two rows in the table');
}

echo $change;

Of course, there's a ton of scope to optimize this, but this is for you to have a head start.
 
Last edited:
So let's assume you're looping through your rows. So it would look something like this
PHP:
$prices = array();
foreach($rows as $row){
    $prices[] = $row->price
}

if(count($prices) == 2){
    list($original, $new) = $prices;
 
    $diff = (int) $original - (int) $new;
    $percent = number_format(((int)$new*100)/(int)$original, 2);
    if($diff == 0){
        $change = 0;
    } else if($diff > 0){
        $change = -$percent;
    } else {
        $change = $percent;
    }
} else {
      die('Did not find two rows in the table');
}

echo $change;

Of course, there's a ton of scope to optimize this, but this is for you to have a head start.
Thanks but output from this is 100 for each
 
Back
Top Bottom