asort PHP Array and keep one entry at the top

心已入冬 提交于 2019-12-11 14:44:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!