2012-04-01 54 views
0
Armstuff > xxxxx 
Uncategorized 
Biler > test 
HOVED > SUB 
Computere > Software 
Smykker 
Computere > Komponenter > RAM 
sss > bbb > kkk 
Computere > Komponenter > Harddiske 
gg 
Computere > Gadgets 
Biler > Ekstraudstyr 
sss > ddd 

這是我的類別列表,通過這個代碼輸出:排序類的名字與PHP數組

<?php 
foreach($categories as $category) 
{ 
    echo $category['name'] . " <br />"; 
} 
?> 

現在$類別子類別名稱被正確定義,以前在代碼通過:

foreach($categories as &$category) 
{ 

    $parent = $category['parent']; 
    while($parent > 0) 
    { 
     $parent_row = $db->select('name', 'paraent')->from('categories')->where('id', '=', $parent)->execute()->as_array(); 
     $parent_row = $parent_row[0]; 
     $category['name'] = $parent_row['name'] . " > {$category['name']}"; 
     $parent = $parent_row['parent']; 

    } 
} 

祝輸出到輸出字母,所以從上面的例子中,它應該輸出類似:

Armstuff > xxxxx 
Biler > test 
Biler > Ekstraudstyr 
Computere > Gadgets 
Computere > Komponenter > Harddiske 
Computere > Komponenter > RAM 
Computere > Software 
gg 
HOVED > SUB 
Smykker 
sss > bbb > kkk 
sss > ddd 
Uncategorized 

我試過簡單的sort(),asort(),但他們不會爲我工作。我怎樣才能做到這一點?感謝在前進

+0

它不善於在循環中運行那麼多查詢 – safarov 2012-04-01 09:52:38

回答

0

嘗試usort,因爲你可以定義自己的比較器(http://at2.php.net/manual/de/function.usort.php)

例子:

function cmpCategories($a, $b) { 
    if ($a["name"] == $b["name"]) { 
     return 0; 
    } 
    return ($a["name"] < $b["name"]) ? -1 : 1; 
} 

usort($categories, "cmpCategories");