php_joe Posted March 2, 2007 Share Posted March 2, 2007 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 More sharing options...
magnetica Posted March 2, 2007 Share Posted March 2, 2007 Can we see your SQL query? Link to comment https://forums.phpfreaks.com/topic/40841-sorting-columns-in-a-table/#findComment-197744 Share on other sites More sharing options...
php_joe Posted March 2, 2007 Author Share Posted March 2, 2007 There's no query, what you see is what I have: a text file and a php file. The table on the text file is row separated by \n and column separated by | Link to comment https://forums.phpfreaks.com/topic/40841-sorting-columns-in-a-table/#findComment-197747 Share on other sites More sharing options...
php_joe Posted March 2, 2007 Author Share Posted March 2, 2007 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 Link to comment https://forums.phpfreaks.com/topic/40841-sorting-columns-in-a-table/#findComment-197774 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.