Sorting an array of SimpleXML objects

后端 未结 5 1209

I\'ve read what I\'ve found on Stackoverflow and am still unclear on this.

I have an array of SimpleXML objects something like this:

array(2) {
  [0]         


        
5条回答
  •  [愿得一人]
    2020-12-02 01:05

    The usort function allows to you tell PHP

    Hey, you! Sort this array I'm giving you with this function I wrote.

    It has nothing specifically to do with SimpleXML. It's a generic function for sorting PHP built-in array data collection.

    You need to write a function, instance method, or static method to sort the array. The second argument to usort accepts a PHP Callback, which is a pseudo-type that lets you specify which function, instance method, or static method.

    The function you write will accept two arguments. These will be two different values from your array

    function cmp($a, $b)
    {
                if ($a == $b) {
                    return 0;
                }
                if($a < $b) {
                    return -1;
                }
                if($a > $b) {
                    return 1;
                }
    }
    

    You need to write this function to return one of three values.

    If $a == $b, return 0
    If $a > $b, return -1
    if $a > $v, return 1  
    

    When you call usort, PHP will run through your array, calling your sorting function/method (in this case cmp over and over again until the array is sorted. In your example, $a and $b will be SimpleXML objects.

提交回复
热议问题