简体   繁体   中英

Reverse Sort by particular column for each loop in php

This is csv file :

40405,Vodafone,2
405806,Aircel,1
41303,Etisalat,1
45201,MobilFone,3
51010,Telkomsel,1
63903,Zain,1
63905,yu,2
64005,Airtel,1

I tried using the rsort, ksort, asort, but unable to sort according to the column. Echoing using the for each loop in php : I am trying to sort the whole data according to the 3rd column in reverse order( descending) ,

$f = fopen("file.csv", "r");

while (($line = fgetcsv($f)) !== false)
{

        echo "<tr id='trdata'>";
        foreach ($line as $cell)
        {
                echo "<td>" . htmlspecialchars($cell). "</td>";
        }
        echo "</tr>\n";

}

Thanks.

$f = fopen("file.csv", "r");

$fileData = array();
while (($line = fgetcsv($f)) !== false) {
    $fileData[] = $line;
}

echo arrayAsTable($fileData) . "<br />";

usort($fileData, function($a, $b) {
    return $b[2] - $a[2];
});

echo arrayAsTable($fileData);

function arrayAsTable($array)
{
    $out = "<table>";
    foreach ($array as $line) {
        $out .= "<tr id='trdata'>";
        foreach ($line as $cell) {
            $out .= "<td>" . htmlspecialchars($cell) . "</td>";
        }
        $out .= "</tr>";

    }
    $out .= "</table>";
    return $out;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM