I have a xml file loaded simplexml, and I need to sort the fields by price, or by author or title. How could I do? Is it ok do it using xpath or another way? I saw a similar
Sort your simplexml like this:
function sort_obj_arr
written by GZipp in this post
$xml = simplexml_load_string($xmlstr, 'SimpleXMLElement', LIBXML_NOCDATA);
$books = $xml->xpath("//libro");
echo "<pre>";
print_r($books);
echo "</pre>";
$field = 'precio';
sort_obj_arr($books,$field,SORT_DESC);
echo "<pre>";
print_r($books);
echo "</pre>";
function sort_obj_arr(& $arr, $sort_field, $sort_direction)
{
$sort_func = function($obj_1, $obj_2) use ($sort_field, $sort_direction)
{
if ($sort_direction == SORT_ASC) {
return strnatcasecmp($obj_1->$sort_field, $obj_2->$sort_field);
} else {
return strnatcasecmp($obj_2->$sort_field, $obj_1->$sort_field);
}
};
usort($arr, $sort_func);
}
Live demo @ http://codepad.viper-7.com/QvLqIq
i know it sounds dumb at first: but map the data in an array and use a custom array callback for usort
if you want to do it right right you will develop something that is called a paginator, which takes care of limit the result displayed on the page and lets you use custom filters.