问题
I have a PHP array
I want to sort it alphabetically and keep a precise entry at the top:
$arr = array ("Orange", "Banana", "Strawberry", "Apple", "Pear");
asort($arr);
Now this will output:
Apple, Banana, Orange, Pear, Strawberry
I want it to keep Orange as the first entry then reorder the others:
Orange, Apple, Banana, Pear, Strawberry
Thanks.
回答1:
Get first element from array, then return it back:
$arr = array ("Orange", "Banana", "Strawberry", "Apple", "Pear");
$first = array_shift($arr);
asort($arr);
array_unshift($arr, $first);
Update with unknown orange
position:
$arr = array ("Banana", "Orange", "Strawberry", "Apple", "Pear");
// $k is index of "Orange" in array
$k = array_search('Orange', $arr);
// store element with founded $k in a variable
$orange = $arr[$k];
// remove $k element from $arr
// same as `unset($arr[$k]);`
array_splice($arr, $k, 1);
// sort
asort($arr);
// add element in the beginning
array_unshift($arr, $orange);
回答2:
You can pass in an element to keep at the top using a custom function and uasort
:
$keep = 'Orange';
uasort($arr, function ($lhs, $rhs) use ($keep) {
if ($lhs === $keep) return -1;
if ($rhs === $keep) return 1;
return $lhs <=> $rhs;
});
It shouldn't matter where Orange is in the array, it'll find its way to the front.
Edit: Note, the <=>
operator requires PHP 7. You can replace with a call to strcmp
if you're using 5
来源:https://stackoverflow.com/questions/46040873/asort-php-array-and-keep-one-entry-at-the-top