Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sort XML Files
#1
Could anyone give me some pointers on how to sort an array of xml files by a node.

I am trying to find all the files in a 'products' directory and display the results as description, pic, price etc.. I have accomplished that, but I need them sorted by price.
Reply
#2
I'm interested in this as well. Can you give an example excerpt from the array?
Reply
#3
mikeh Wrote:Could anyone give me some pointers on how to sort an array of xml files by a node.

I am trying to find all the files in a 'products' directory and display the results as description, pic, price etc.. I have accomplished that, but I need them sorted by price.

Here is a sample code for reading product files and sorting them by price and name:

Code:
function myplugin_compare_price($a, $b) {
  $result = $a['price'] - $b['price']; // sort by price - or $b['price'] - $a['price']
  return $result == 0 ? strcmp($a['name'],$b['name']) : $result; // sort by name if same price
}

// read product files into array $products:
$products = array();
$productdir = 'path/to/dir/';
$dir_handle = @opendir($productdir);
while ($filename = readdir($dir_handle)) {
  if (strrpos($filename,'.xml') === strlen($filename)-4) {
    $data = getXML($productdir . $filename);
    $products[] = array('name' => (string) $data->name, 'price' => (int) $data->price, ...);
  }
}
// sort by user function:
usort($products, 'myplugin_compare_price');
I18N, I18N Search, I18N Gallery, I18N Special Pages - essential plugins for multi-language sites.
Reply
#4
mvlcek Wrote:
mikeh Wrote:Could anyone give me some pointers on how to sort an array of xml files by a node.

I am trying to find all the files in a 'products' directory and display the results as description, pic, price etc.. I have accomplished that, but I need them sorted by price.

Here is a sample code for reading product files and sorting them by price and name:

Code:
function myplugin_compare_price($a, $b) {
  $result = $a['price'] - $b['price']; // sort by price - or $b['price'] - $a['price']
  return $result == 0 ? strcmp($a['name'],$b['name']) : $result; // sort by name if same price
}

// read product files into array $products:
$products = array();
$productdir = 'path/to/dir/';
$dir_handle = @opendir($productdir);
while ($filename = readdir($dir_handle)) {
  if (strrpos($filename,'.xml') === strlen($filename)-4) {
    $data = getXML($productdir . $filename);
    $products[] = array('name' => (string) $data->name, 'price' => (int) $data->price, ...);
  }
}
// sort by user function:
usort($products, 'myplugin_compare_price');

That did the trick Big Grin
Thanks!
Reply




Users browsing this thread: 1 Guest(s)