开发者

Sort array starting with given value

开发者 https://www.devze.com 2023-01-12 17:16 出处:网络
I would like to sort a php array starting with a value I set Example: $array = array(); $array[\'test\'] = \'banana\';

I would like to sort a php array starting with a value I set

Example:

$array = array();
$array['test'] = 'banana';  
$array['test2'] = 'apple';  
$array['test3'] = 'pineapple';  
$arr开发者_StackOverfloway['test4'] = 'orange';  

How do I sort it so that 'orange' is the first result then it sorts alphabetical from then on.

So it would be

orange

apple

banana

pineapple

Any help on this would be greatly appreciated.


You can create your own custom sorting function and then use usort (or uasort if you want to preserve your array keys -- thanks to Isaac in the comments for the reminder) to sort your array with it:

function sort_fruit($a, $b)
{
  if ($a == $b) return 0;         // If the values are the same, usort expects 0 
  if ($a == "orange") return -1;  // $a is orange, $b is not -> $a comes first
  if ($b == "orange") return 1;   // $b is orange, $a is not -> $b comes first
  return strcmp($a, $b);          // ... otherwise, sort normally
}

usort($array, "sort_fruit");


This might be a little over the top, but I'm not aware of a single method that will do what you are asking:

<?php

$old_array = array(
    1 => 'banana',
    2 => 'apple',
    3 => 'pineapple',
    4 => 'orange'
);

$search = 'orange';

$new_array = array();

if( ($key = array_search($search, $old_array)) !== FALSE)
{
    $new_array[] = $search;
    unset($old_array[$key]);
}

$new_array = array_merge($new_array, asort($old_array));
0

精彩评论

暂无评论...
验证码 换一张
取 消