Sort object(SimpleXMLElement) php

后端 未结 4 1438
北荒
北荒 2020-12-22 04:23

I\'m trying to find a way to sort my array from SimpleXMLElement. I\'d like to sort by start time which I can get from event_start_dt. I\'d also like to sort by room ID as a

4条回答
  •  萌比男神i
    2020-12-22 05:03

    I would just cast it as an array using this function (example function from php.net). But note that this will not sort the XML, rather sort the new array

    /**
    * function xml2array
    *
    * This function is part of the PHP manual.
    *
    * The PHP manual text and comments are covered by the Creative Commons 
    * Attribution 3.0 License, copyright (c) the PHP Documentation Group
    *
    * @author  k dot antczak at livedata dot pl
    * @date    2011-04-22 06:08 UTC
    * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
    * @license http://www.php.net/license/index.php#doc-lic
    * @license http://creativecommons.org/licenses/by/3.0/
    * @license CC-BY-3.0 
    */
    function xml2array ( $xmlObject, $out = array () )
    {
      foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
    
       return $out;
     }
    

    and pass it the XMLObject

    $arrTimes = xml2array(YourSimpleXMLElement);
    

    and then use your original usort function on the new array

     function sortByTime($a, $b){
        $a = strtotime($a['event_start_dt']);
        $b = strtotime($b['event_start_dt']);
        if ($a==$b) 
           return 0;
        return ($a < $b) ? -1 : 1;
     }
    

    Finally

    usort($arrTimes, 'sortByTime');
    

提交回复
热议问题