Mahesh Cholleti
Mahesh Cholleti

Reputation: 19

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.

Upvotes: 1

Views: 631

Answers (1)

littleibex
littleibex

Reputation: 1712

$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;
}

Upvotes: 2

Related Questions