2011-11-10 29 views
1

我遇到了一個問題,我的任何值都沒有以正確的順序結束。使用usx和simplexml

 $xml = file_get_contents('admin/people.xml'); 
     $x = new SimpleXMLElement($xml); 

     $sort=$x->person; 

     function cmp($a, $b){ 
      if ($a->age == $b->age) { 
       return 0; 
      } 
      return ($a->age < $b->age) ? -1 : 1; 
     } 
     usort($sort, 'cmp'); 

     foreach ($sort as $key => $value) { 
      echo "$key: $value->age<br>"; 
     } 

從我讀過的一切,這應該工作,但它沒有。這裏是XML:

 <people> 
      <person> 
       <name>Frank</name> 
       <age>12</age> 
      </person> 
      <person> 
       <name>Jim</name> 
       <age>6023</age> 
      </person> 
      <person> 
       <name>Tony</name> 
       <age>234</age> 
      </person> 
      <person> 
       <name>Bob</name> 
       <age>2551</age> 
      </person> 
      <person> 
       <name>Dave</name> 
       <age>21</age> 
      </person> 
      <person> 
       <name>Trevor</name> 
       <age>56</age> 
      </person> 
      <person> 
       <name>Mike</name> 
       <age>89</age> 
      </person> 
     </people> 

而我得到的結果是這是,這是沒有一種秩序!

0: 6023 
2: 21 
3: 234 
4: 12 
6: 56 
7: 2551 
8: 89 

任何想法?

非常感謝......

+0

可能重複的[PHP與SimpleXML排序問題](http://stackoverflow.com/questions/3023029/php-sorting-issue-with-simplexml) – hakre

回答

1
  • usort接受數組。
  • 當您比較兩個SimpleXMLElements時,您應該施放它們。

因此,代碼

$sort=$x->person; 

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

改變

$sort = array(); 
foreach ($x->person as $person) { 
     $sort[] = $person; 
} 

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

會給你正確的結果。

+0

這很好,非常感謝xdazz :) – Tim

1

爲了使用usort你需要你的SimpleXMLElement轉換成數組。這裏是一個快速的方法來做到這一點(http://www.php.net/manual/en/book.simplexml.php#105330):

$xml = file_get_contents('admin/people.xml'); 
$x = new SimpleXMLElement($xml); 
$json = json_encode($x); 
$xml_array = json_decode($json,TRUE); 
$sort = $xml_array['person']; 

現在,你可以通過$sortusort,它會正常工作。將$a->age替換爲$a['age']