Jump to content

Alphabetical Order


Schlo_50

Recommended Posts

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

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

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

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.