Posts: 661
Threads: 52
Joined: Feb 2011
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.
Posts: 524
Threads: 48
Joined: Mar 2011
I'm interested in this as well. Can you give an example excerpt from the array?
Posts: 2,094
Threads: 54
Joined: Jan 2011
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');
Posts: 661
Threads: 52
Joined: Feb 2011
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
Thanks!