2011-12-02 23 views
0

我有一個多維數組(標準的RSS頻道 - 項目標題),我試圖按標題排序。我正在使用SimpleXML並創建了SimpleXML對象中的項目數組。然後我從items數組中創建了另一個標題數組。然後我使用array_multisort()按標題對items數組進行排序。PHP SimpleXML Array_multisort()作品種類

這是一種工作。有122個項目。排序依次放置2個項目,然後依次排列80個項目,然後是38個項目,然後依次排列2個項目。但我不確定爲什麼它將它們分成4組。

XML:

<channel> 
    <item> 
     <title>Saved To Serve</title> 
     <guid>http://www.moorelife.org/rss/SavedToServe.xml</guid> 
     <pubDate>Sun, 06 Nov 2011 11:00:00 CST</pubDate> 
    </item> 
    <item> 
     <title>Filled With All The Fullness Of God</title> 
     <guid>http://www.moorelife.org/rss/FilledWithAllTheFullnessOfGod.xml</guid> 
     <pubDate>Mon, 03 Oct 2011 19:00:00 CST</pubDate> 
    </item> 
</channel> 

PHP:

<?php 
$items = array(); 
foreach($data->channel->item as $item) { 
    $items[] = $item; 
} 
$titles = array(); 
foreach($items as $item) { 
    $titles[] = $item["title"]; 
} 
array_multisort($titles, SORT_ASC, $items); 
print "<pre>\n"; 
print_r($items); 
print "</pre>\n"; 
?> 

在XML文件中,保存的發球充滿了豐滿的神(就像樣品)權利之前。分類時,在STS之前,FWATFOG應該是50個左右的項目。在實際輸出中,STS是#2,FWATFOG是#86(在第三個字母分組中)。

我的最終目標是能夠按標題或日期進行排序(最好使用AJAX,因此我們不必處理頁面重新加載)。你們有什麼想法或建議嗎?

JJ

+0

顯然,有工作別的東西在這裏。我試着做SORT_DESC以及創建其他數組('$ pubDates [] = $ item [「pubDate」];'),並且所有輸出都以相同的順序輸出。唯一一次輸出不同的是,如果我輸入了錯誤的值,並且它按xml的方式排序。 – doubleJ

回答

0

你可以直接排序的SimpleXML對象第一:

 
$nodes = array(
    new SimpleXMLElement('<item> 
     <title>Saved To Serve</title> 
     <guid>http://www.moorelife.org/rss/SavedToServe.xml</guid> 
     <pubDate>Sun, 06 Nov 2011 11:00:00 CST</pubDate> 
    </item> 
'), 
    new SimpleXMLElement('<item> 
     <title>Filled With All The Fullness Of God</title> 
     <guid>http://www.moorelife.org/rss/FilledWithAllTheFullnessOfGod.xml</guid> 
     <pubDate>Mon, 03 Oct 2011 19:00:00 CST</pubDate> 
    </item> 
') 
); 

function xsort(&$nodes, $child_name, $order = SORT_ASC) 
{ 
    $sort_proxy = array(); 

    foreach ($nodes as $k => $node) 
    { 
     $sort_proxy[$k] = (string) $node->$child_name; 
    } 

    array_multisort($sort_proxy, $order, $nodes); 
} 

xsort($nodes, 'title', SORT_ASC); 

print_r($nodes); 
+0

這對我來說不起作用(空白頁)。值得一提的是,我使用php4,使用php4類的simplexml(http://www.phpclasses.org/package/4484-PHP-Load-XML-files-in-PHP-4-like-SimpleXML- extension.html)。我沒有想到提及它,因爲它不是問題。它似乎以相同的方式與對象一起工作。我知道它不支持xpath或通配符,但它可能不適用於$ node - > $ child_name或其他東西。 – doubleJ