2011-06-24 49 views
0

感謝許多人誰在這裏幫助我們在Stackoverflow。你們都很棒!現在回答這個問題。我有一個數組:「鴨」,「雞」,「雞蛋」,「豬肉」,「牛排」,「牛肉」,「魚」,「蝦」,「鹿」和「羊肉「。自定義訂單和顯示foreach PHP

我已經列出了要按字母順序顯示的列表。這是一個動態數組,因此它可能並不總是具有所有這些值或按順序排列。我希望「牛排」始終首先出現在旁邊的「頂級選項」旁邊,而其餘的按照字母順序排列,旁邊有「可訂購」。

這裏就是我和$ meat_items作爲數組了迄今:

foreach($meat_items as $meat_item) 
    echo $meat_item . ' Available for Order <br>'; 

我要澄清:牛排可能並不總是陣列的一部分。

+0

「它可能並不總是有所有這些值或者是按照這個順序。」但它會一直有「牛排」嗎? 「牛排」究竟是什麼特別的,你想先列入清單? –

+0

它可能並不總是有牛排。我需要這一點才能脫穎而出,因爲它是該類肉類的最佳選擇之一,而不是名單的底部。其餘的需要按字母順序排列。 – David

+0

難道你不能只是從數組中刪除「牛排」,回聲它,然後回聲陣列中的一切? –

回答

3

因爲你總是希望牛排它首先出現,硬代碼:

if (in_array("steak", $meat_items)) { 
    `echo "Steak: Top Choice";` 
} 

排序您的陣列字母:

sort($meat_items); 

然後依次通過您的數組,呼應所有項目牛排:

foreach ($meat_items as $meat_item) { 
    if ("steak" != $meat_item) { 
     echo $meat_item . ' Available for Order<br />'; 
    } 
} 
+0

@GeorgeCummins在sort()中加入。他仍然希望剩下的物品分類。 – FinalForm

+0

我應該澄清一下:牛排可能不總是陣列的一部分。 – David

+0

@FinalForm:他說他已經解決了這個問題,但我添加了它來讓你開心。 –

0
if (!empty($meat_items['steak'])) 
{ 
    echo 'Steak Top Choice <br >'; 
    unset($meat_items['steak']); 
} 

sort($meat_items); 

foreach($meat_items as $meat_item) 
    echo $meat_item . ' Available for Order <br>'; 
+0

您在'unset()'函數中缺少括號。 – iamandrus

+0

@itamake修復。 – FinalForm

+0

我應該澄清:牛排可能並不總是陣列的一部分。 – David

0

更通用的方法是告訴PHP如何對項目進行排序,方法是定義一個喜歡「頂級選項」的排序「比較」,然後將它傳遞給usort

我真的不知道PHP,但類似:

function prefer_top($a, $b) { 
    /* We can modify this array to specify whatever the top choices are. */ 
    $top_choices = array('Steak'); 
    /* If one of the two things we're comparing is a top choice and the other isn't, 
     then it comes first automatically. Otherwise, we sort them alphabetically. */ 
    $a_top = in_array($a, $top_choices); 
    $b_top = in_array($b, $top_choices); 
    if ($a_top && !$b_top) { return -1; } 
    if ($b_top && !$a_top) { return 1; } 
    if ($a == $b) { return 0; } 
    return ($a < $b) ? -1 : 1; 
} 

usort($meat_items, "prefer_top"); 

// and then output them all in order as before.