Denny
Denny

Reputation: 21

Limit For each output AFTER if statement

Good morning,

I try to get a top-10 of countries, but want to exclude a few countries from the output. I realize the following code is filtering the 10 results, so when one of the countries is in it will be filtered. the result is only a top 6 for example. But I need a top-10. Can anybody tell me how to limit the For Each statement to 10 without taking the 4 countries into account?

Thank you very much!

<table class="table" >
    <thead>
        <tr>
            <th><?=l('Top 10 landen')?></th>
            <th><?=l('Bezoek')?></th>
        </tr>
    </thead>
    <tbody>
        <?php foreach(array_slice($countries, 0, 10) as $country => $cdata)
        if($country != 'United States' && $country != 'Canada' && $country != 'China' && $country != 'Mexico') {
        ?>
        <tr>
            <td><?=$country?></td>
            <td><?=$cdata['views']?></td>
        </tr>          
        <?php } ?>
    </tbody>
</table>

Upvotes: 2

Views: 80

Answers (2)

Sachin
Sachin

Reputation: 2148

I don't have much knowledge of php but I think this can solve your problem..

You can take one integer variable i = 0 and increment it with i++; in each if loop and break for loop when i > 10..

<table class="table" >
    <thead>
        <tr>
            <th><?=l('Top 10 landen')?></th>
            <th><?=l('Bezoek')?></th>
        </tr>
    </thead>
    <tbody>
        <?php $i = 0;
foreach ($countries as $country => $cdata) {
        if($country != 'United States' && $country != 'Canada' && $country != 'China' && $country != 'Mexico') {
        ?>
        <tr>
            <td><?=$country?></td>
            <td><?=$cdata['views']?></td>
        </tr>          
        <?php 

            $i++;
        }
if($i > 10) break; } ?>
    </tbody>
</table>

Upvotes: 2

Giorgio
Giorgio

Reputation: 1970

If $countries array is obtained from a MySQL query, you can filter it within MySQL query:

SELECT id FROM `countries` WHERE id NOT IN("United States", "Canada", "China", "Mexico") LIMIT 10

You can obviously build your query to accept a configurable array of excluded countries from PHP. This is faster, since avoids you to slice and filter resulting array. With a one-shot query you can get what you want.

Upvotes: 1

Related Questions