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
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 ;)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.