Jump to content

Sorting columns in a table?


php_joe

Recommended Posts

Hi, I'm trying to write a snippit that will sort rows in a table based on a column's value.

 

My test table is this:

0|1|2|3|4
1|2|3|4|0
2|3|4|0|1
3|4|0|1|2
4|0|1|2|3

 

And the code I have so far is:

<?
if(!$sort) $sort = '0';
$line = file("./test.txt");
foreach($line as $key => $row){
$col = explode("|", $row);
$array2 = "$col[$sort]";
$result = array_merge($array2, $col);
$new_row[$key] = implode("|", $result);
}
sort($new_row);
foreach($new_row as $key => $value){
echo "<div>$value</div>";
}
?>

 

Which works... kind of.

 

The problem is that the sort() function is sorting the output as text, not numbers, so that when the values go over 9 (i.e. 10) then instead of being sorted as 1, 2, 3, 10, 11 it sorts it as 1, 10, 11, 2, 3.

 

What can I change to make it sort the values as a number?

 

Or is there a better way to sort a table using a column's value (other than column 0)?

Link to comment
https://forums.phpfreaks.com/topic/40841-sorting-columns-in-a-table/
Share on other sites

OK, I figured it out:

 

<?
if(!$sort) $sort = '0';
$line = file("./test.txt");
foreach($line as $key => $row){
$col = explode("|", $row);
$array2 = "$col[$sort]";
$result = array_merge($array2, $col);
$new_row[$key] = implode("|", $result);
}
if(is_numeric($array2)){
sort($new_row, SORT_NUMERIC);
}else{
sort($new_row);
}
foreach($new_row as $key => $value){
echo "<div>$value</div>";
}
?>

 

Still.... if anyone knows a better way to sort a table from a text file, let me know ;)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.