自定义订单并显示foreach PHP


custom order and display foreach PHP

感谢在Stackoverflow上帮助我们的许多人。你们都很棒!现在开始提问。我得到了以下值的数组:"鸭子"、"鸡肉"、"鸡蛋"、"猪肉"、"牛排"、"牛肉"、"鱼"、"虾"、"鹿"answers"羊肉"

我已经得到了按字母顺序显示的列表。这是一个动态数组,因此它可能并不总是具有所有这些值或按该顺序排列。我希望"牛排"总是先出现,旁边有"首选",而其余的则按字母顺序排列,旁边是"可供订购"。

以下是我迄今为止使用$meat_items作为数组得到的结果:

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

我应该澄清一下:牛排可能并不总是数组的一部分。

因为你总是希望牛排先出现,所以硬编码:

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 />';
    }
}
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>';

一种更通用的方法是告诉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.