我有以下數組,我試圖按比分排序,然後匹配,然後名稱,但我的方法不工作。任何人都能看到爲什麼按子數組排序多維數組
最終順序應該是4,3,5,
的usort
我用的是在底部。
[3] => Array
(
[name] => DrayTek Vigor 2130Vn VoIP/WiFi Router
[matches] => Array
(
[0] => voip
)
[score] => 3
)
[4] => Array
(
[name] => DrayTek Vigor 2750n VDSL Wireless Router
[matches] => Array
(
[0] => 2750
)
[score] => 3
)
[5] => Array
(
[name] => DrayTek Vigor 2850Vn VDSL/ADSL VoIP Router
[matches] => Array
(
[0] => voip
)
[score] => 3
)
邏輯
1. all have the same score, so no change in order
2. 4 has 2750 in matches[0] which assuming numbers come before letters, moves 4 up
** the order now should be 4,3,5
3. as 3 and 5 have the same matches[], no change in order
4. 3's name naturally comes before 5 but since its already above, no change
** final order should be 4,3,5
排序結果,得分最高的第一個,接着匹配數組,然後命名
function cmp($a, $b)
{
if ($a['score'] < $b['score'])
return 1;
elseif ($a['score'] > $b['score'])
return -1;
elseif (! array_diff($a['matches'], $b['matches']))
return 1;
elseif (! array_diff($b['matches'], $a['matches']))
return -1;
elseif (($c = strnatcmp(strtolower($a['name']), strtolower($b['name']))) !== 0)
return $c;
else
return 0;
}
usort($this->results['rows'], "cmp");
我不明白你試圖用火柴數組排序該怎麼辦... –
@馬克 - 我想組「匹配」陣列在一起。由於3和5都具有相同的分數並與數組匹配,因此它們應該一個接一個出現,但它們之間用4分隔。 – Christian
仍然沒有得到它。 2750爲什麼擊敗voip? –