user1880469
user1880469

Reputation: 11

PHP sort inside while

I want the echo to be sorted by the value of $match_count. The highest number should be at the top.

while($row = mysql_fetch_array($result)) {
    $num_kanal = count(explode(' ', $row['kanaler']));

    $pr_kanal = $row['pris'] / $num_kanal;
    $pr_kanal = number_format((float)$pr_kanal, 2, '.', '');

    $farve = '#6a6a6a;';

    if ($_POST['kanaler']) {

        $getkan = implode($_POST['kanaler'], ' ');
        $kan = $row['kanaler'];
        $match_count = count(TheMatch($kan, $getkan));
        $match = ' Match = '.$match_count;
        }

        // I WANT THIS ECHO TO BE SORT BY THE VALUE OF '$match_count' HIGEST NR IN TOP //
        echo'<tr>
            <td style="background-color:'.$farve.'"><p>
            ' . $row['udbyder'] . ' '.$_POST['kanaler'].'
            </p></td>
    </tr>';
    }
}

Upvotes: 0

Views: 2497

Answers (2)

randiel
randiel

Reputation: 290

You can use array_multisort too:

<?php 
array_multisort($match_count, SORT_DESC, $array_values_to_print);

foreach ($match_count as $result) {
    echo '<tr><td style="background-color:...</tr>';
}
?>

the first array determines the index.

Upvotes: 0

Mario
Mario

Reputation: 36487

You'd have to buffer your output/values while iterating over your array, sort it and then print it. Something like this:

$results = array();
while($row = ...) {
    ...
    $results[] = array($match_count, '<tr><td style="background-color:...</tr>');
}

uasort($results, my_comp);

foreach($results as $result)
    echo $result[1];

This will sort the array and then print it based on this sorting function:

function my_comp($left, $right) {
    return $left[0] > $right[0]; // to be honest I'm not 100% sure right now whether you'd need < or > for the right sorting order
}

Upvotes: 1

Related Questions