sorting the table fields using simple XML and xpath

前端 未结 2 1628
误落风尘
误落风尘 2020-12-07 06:17

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

相关标签:
2条回答
  • 2020-12-07 06:58

    Sort your simplexml like this:

    function sort_obj_arrwritten 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

    0 讨论(0)
  • 2020-12-07 07:10

    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.

    0 讨论(0)
提交回复
热议问题