asort PHP Array and keep one entry at the top

2019-08-23 15:45发布

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.

2条回答
祖国的老花朵
2楼-- · 2019-08-23 15:48

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

查看更多
smile是对你的礼貌
3楼-- · 2019-08-23 15:50

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);
查看更多
登录 后发表回答