2012-01-19 51 views
1

我已經使用array_merge組合了兩個數組,現在需要按字母順序對它們進行排序。問題是我需要比較兩個不同的鍵,PHP usort比較函數

例如

[0] => stdClass Object 
(
[id] => 16 
[title] => Oranges 
) 

[1] => stdClass Object 
(
[id] => 23 
[title] => Apples 
) 

[2] => stdClass Object 
(
[id] => 16 
[name] => Bananas 
) 

我需要相互比較,以及與「標題」特性「名稱」屬性,然後進行排序的字母順序,(忽略ID),使我的結果將是:

蘋果
香蕉
橙子

但是,函數我這裏有:

function compareItems($a, $b) 
{ 
if ($a->title < $b->title) return -1; 
if ($a->title > $b->title) return 1; 
if ($a->name < $b->name) return -1; 
if ($a->name > $b->name) return 1; 
return 0; 
} 

usort($array, "compareItems"); 

...不合並,但排序一組屬性(標題),那麼其他的(名字),從而給我:

蘋果
橙子
香蕉

我希望我能修改這個函數將兩者合併 - 我不是一個真正的PHP程序員,所以任何幫助都非常感謝!

在此先感謝。

回答

3

比較函數我有下面應該爲你工作:

function compareItems($a, $b) 
{ 
    $x = isset($a->title) ? $a->title : $a->name; 
    $y = isset($b->title) ? $b->title : $b->name; 
    return strcmp($x, $y); 
} 
+0

謝謝你的快速反應 - 完美的作品! – traummaschine

+0

@RT:很高興幫助!請記住通過點擊綠色選中標記來回答這個問題。 –