Schlo_50 Posted April 16, 2008 Share Posted April 16, 2008 Hey guys, Just a quick one. How can I get my code below to order the contents of my .txt file in alphabetical order according to $name? <?php $file = file("names.txt"); foreach($file as $key => $val){ $data[$key] = explode("|", $val); $id = $data[$key][0]; $name = $data[$key][1]; $example = $data[$key][2]; $desc = $data[$key][3]; $out = "<strong><a href=\"$example\" target=\"_blank\">$name</a></strong><br /> $desc <br /><br />"; print( $out ); } ?> Thanks for any help! Link to comment https://forums.phpfreaks.com/topic/101361-alphabetical-order/ Share on other sites More sharing options...
craygo Posted April 16, 2008 Share Posted April 16, 2008 try looking here http://us3.php.net/manual/en/function.sort.php there are also other types or array sorts, look through them. Ray Link to comment https://forums.phpfreaks.com/topic/101361-alphabetical-order/#findComment-518452 Share on other sites More sharing options...
obsidian Posted April 16, 2008 Share Posted April 16, 2008 The array_multisort() function is what you are after here. Try something like this: <?php $res = file('names.txt'); $data = array(); foreach ($res as $r) { $row = explode('|', $r); $data[] = array( 'id' => $r[0], 'name' => $r[1], 'example' => $r[2], 'desc' => $r[3] ); } // Now to sort the results foreach ($data as $k => $row) { $id[$k] = $row['id']; $name[$k] = $row['name']; $example[$k] = $row['example']; $desc[$k] = $row['desc']; } array_multisort($name, SORT_ASC, $data); // Test your result echo "<pre>" . print_r($data, TRUE) . "</pre>"; ?> Hope this helps! Link to comment https://forums.phpfreaks.com/topic/101361-alphabetical-order/#findComment-518456 Share on other sites More sharing options...
rhodesa Posted April 16, 2008 Share Posted April 16, 2008 Another way: <?php $file = 'names.txt'; $sort_col = 1; //Column index to sort on $data = array(); $sort_vals = array(); $lines = file($file); foreach($lines as $n=>$line){ $data[$n] = explode("|",$line); $sort_vals[$n] = $data[$n][$sort_col]; } array_multisort($sort_vals,$data); foreach($data as $row){ $id = $row[0]; $name = $row[1]; $example = $row[2]; $desc = $row[3]; print "<strong><a href=\"$example\" target=\"_blank\">$name</a></strong><br /> $desc <br /><br />"; } ?> Link to comment https://forums.phpfreaks.com/topic/101361-alphabetical-order/#findComment-518459 Share on other sites More sharing options...
Schlo_50 Posted April 16, 2008 Author Share Posted April 16, 2008 I started looking at natsort, but the examples you guys have come up with are great. Thanks Link to comment https://forums.phpfreaks.com/topic/101361-alphabetical-order/#findComment-518464 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.