1

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.

Mahesh Cholleti
  • 19
  • 1
  • 10

1 Answers1

2
$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;
}
littleibex
  • 1,705
  • 2
  • 14
  • 35
  • yes, I got it ...Thanks very much...can you please explain usort($fileData, function($a, $b) { return $b[2] - $a[2]; }); this part i din't understand... – Mahesh Cholleti Feb 23 '15 at 08:50
  • @MaheshCholleti Sorting works by comparison. For example, if you wanted to sort (4,2,5,1) in ascending order you would get (1,2,4,5) because every time there is a comparison between any two items in the array, you would choose the smaller one of them and place it in the beginning. In our case, the two item, $a and $b, are arrays and we want the array with smaller value of the last column to be first, and hence, the statement return $b[2] - $a[2]; I can explain more in chat. Also, please +1 the answer – littleibex Feb 23 '15 at 09:08
  • But for +1 answer , I required 15 reputations ... I don't had........and K , doing the comparison with two values in array , but return $b[2] - $a[2]; ...I din't get...?..please explain.. – Mahesh Cholleti Feb 23 '15 at 09:20
  • @MaheshCholleti The function needs to return an integer. If the return value is negative that means $a is "smaller" than $b, if it's equal to zero then $a=$b and if it's positive then $a is greater than $b. When the sorting is complete, it lists the items from smallest values of $a to the largest. I hope this explanation makes sense. I suggest you read about sorting algroithms and how they are implemented in Java, C++ and PHP to get a better understanding. – littleibex Feb 23 '15 at 10:50
  • Thanks so much...now I understand...I am struggling in how its got....thanks so much...can you please suggest....is there any link...to read about the sorting algorithms...so that I can practice on it... – Mahesh Cholleti Feb 23 '15 at 13:03