我想从我设置的值开始排序一个php数组
例:
$array = array();
$array['test'] = 'banana';
$array['test2'] = 'apple';
$array['test3'] = 'pineapple';
$array['test4'] = 'orange';
Run Code Online (Sandbox Code Playgroud)
我如何对它进行排序,以便"橙色"是第一个结果,然后从那时起按字母顺序排序.
所以它将是
橙色
苹果
香蕉
菠萝
任何有关这方面的帮助将不胜感激.
您可以创建自己的自定义排序功能,然后使用usort(或者uasort如果您想保留数组键 - 感谢Isaac在提醒的注释中),可以使用它对数组进行排序:
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");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
883 次 |
| 最近记录: |