You are here:  » Simple Sorting


Simple Sorting

Submitted by andras on Wed, 2009-05-06 17:15 in

I seem to remember to have seen a simple sorting example on your site, but have not been able to (re)locate it. http://www.magicparser.com/node/861 is NOT it.
Can you point me to one if such indeed exists, or else advise on how simply I could alphabetize my records based on an arbitrary record property?

Thanks.

Submitted by support on Wed, 2009-05-06 17:35

Hi Andras,

I don't recall a thread specifically regarding alphabetic sort, but it is straight forward to do using PHP's usort() and strcmp() functions.

As with the method described in node 861, the records will have to be first read into a global array ($records in this example), and then after the sort you can process each record easily using foreach().

Here's an example which will alphabetically sort RSS feed items by TITLE, and then display each title. Let me know if you have any problems modifying this for your own purposes...

<?php
  
require("MagicParser.php");
  
$records = array(); // global array to hold records
  
function myRecordHandler($record)
  {
    global 
$records;
    
$records[] = $record// add $record to global $records array
  
}
  
// parse file to load $records
  
MagicParser_parse("rss.xml","myRecordHandler","xml|RSS/CHANNEL/ITEM/");
  
// user sort function for usort()
  
function mySortFunction($record1,$record2)
  {
    return 
strcmp($record1["TITLE"],$record2["TITLE"]);
  }
  
// sort $records using mySortFunction
  
usort($records,"mySortFunction");
  
// finally process each record using foreach(), just as if in myRecordHandler
  
foreach($records as $record)
  {
    print 
"<p>".$record["TITLE"]."</p>";
  }
?>

Hope this helps!
Regards,
David.

Submitted by andras on Thu, 2009-05-07 14:17

Thanks. I think I have usort() down now ;^)