Question

Within opencart, i am developing the admin panel.

I want to show say, the top 10 stores and their respective visits.

at the moment, i have this information within a table and my php loop is this.

  <?php foreach ($stores as $store) { ?>
    <?php echo $store['name']?>
    <?php echo number_format($store['visitor'])?>
  <?php } ?>

This returns data in a big mess but the data IS there!

Alesso 20
Alice in Chains 32
Amy Winehouse 27
Avenged Sevenfold 136
Axewound 30
Axwell 6
Backstreet Boys 24

And so on.... for about 100 Different stores.

What i want to know is, in the foreach loop i wish to only display the top say, 10 stores. the top stores with the most visits, now i have the data, but how do i go about sorting this in a foreach to only show the top 10?

Many thanks Sean

Was it helpful?

Solution

You can use array_multisort

Update based on your code:

$limit=10;  
foreach ($stores as $key => $row) {
  $store[$key]  = $row['name'];
  $visitor[$key] = $row['visitor'];
}

array_multisort($visitor, SORT_DESC, $store, SORT_ASC, $stores);

$stores = array_chunk($stores, $limit);

foreach ($stores as $store) {
  echo $store['name'];      
  echo number_format($store['visitor']);        
}  

OTHER TIPS

You have several solution :

It should give something like this :

function cmp($a, $b)
{
    if ($a['visitor'] == $b['visitor']) {
        return 0;
    }
    return ($a['visitor'] < $b['visitor']) ? -1 : 1;
}

usort($store, "cmp");

$storeIndex= 0;
while($storeIndex< 10) {
        echo $store[storeIndex]['name'];
        echo number_format($store[storeIndex]['visitor']);

$storeIndex++;
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top