Reputation: 809
Thanks to the many folks who help us out here on Stackoverflow. You all are awesome! Now to the question. I've got an array for the following values: "duck", "chicken","egg", "pork", "steak", "beef", "fish", "shrimp", "deer", and "lamb."
I've gotten the list to display in Alphabetical order. This is a dynamic array, so it may not always have all these values or be in that order. I'd like to have "Steak" always appear first with "Top Choice" next to it, while keeping the rest in alphabetical order with "Available for Order" next to them.
Here's what I've got thus far with $meat_items as the array:
foreach($meat_items as $meat_item)
echo $meat_item . ' Available for Order <br>';
I should clarify: Steak may NOT always be a part of the array.
Upvotes: 0
Views: 3008
Reputation: 28906
Since you always want steak to appear first, hard code it:
if (in_array("steak", $meat_items)) {
`echo "Steak: Top Choice";`
}
Sort your array alphabetically:
sort($meat_items);
Then loop through your array, echoing all items except the steak:
foreach ($meat_items as $meat_item) {
if ( "steak" != $meat_item ) {
echo $meat_item . ' Available for Order<br />';
}
}
Upvotes: 3
Reputation: 61607
A more general purpose way to do this is to tell PHP how to sort the items, by defining a sorting "comparison" that prefers the "top choices", and then passing it to usort
.
I don't really know PHP, but something like:
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.
Upvotes: 0
Reputation: 5974
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>';
Upvotes: 0