按自定义顺序对数组的 php 数组进行排序 [英] Sorting a php array of arrays by custom order
问题描述
我有一个数组:
Array (
[0] => Array (
[id] = 7867867,
[title] = 'Some Title'),
[1] => Array (
[id] = 3452342,
[title] = 'Some Title'),
[2] => Array (
[id] = 1231233,
[title] = 'Some Title'),
[3] => Array (
[id] = 5867867,
[title] = 'Some Title')
)
需要按照特定的顺序:
- 3452342
- 5867867
- 7867867
- 1231233
我该怎么做?我之前对数组进行过排序,并阅读了很多关于它的其他文章,但它们总是基于比较(即 valueA
How would I go about doing that? I have sorted arrays before, and read plenty of other posts about it, but they are always comparison based (i.e. valueA < valueB).
感谢帮助.
推荐答案
您可以使用 usort()
来精确指定数组的排序方式.在这种情况下,可以在比较函数中使用 $order
数组.
You can use usort()
to dictate precisely how the array is to be sorted. In this case, the $order
array can be used within the comparison function.
下面的示例使用 closure
使生活更轻松.
The example below uses a closure
to make life easier.
$order = array(3452342, 5867867, 7867867, 1231233);
$array = array(
array('id' => 7867867, 'title' => 'Some Title'),
array('id' => 3452342, 'title' => 'Some Title'),
array('id' => 1231233, 'title' => 'Some Title'),
array('id' => 5867867, 'title' => 'Some Title'),
);
usort($array, function ($a, $b) use ($order) {
$pos_a = array_search($a['id'], $order);
$pos_b = array_search($b['id'], $order);
return $pos_a - $pos_b;
});
var_dump($array);
这项工作的关键是要比较值,即 $order
数组中 id
的位置.
The key to this working is having the values that are being compared, be the positions of the id
s within the $order
array.
比较函数的工作原理是在 $order
数组中查找要比较的两个项目的 id 的位置.如果 $a['id']
在 $order
数组中出现在 $b['id']
之前,则返回值function 将是负数($a
更少,因此浮动"到顶部).如果 $a['id']
出现在 $b['id']
之后,则该函数返回一个正数($a
大于所以下沉").
The comparison function works by finding the positions of the ids of two items to be compared within the $order
array. If $a['id']
comes before $b['id']
in the $order
array, then the return value of the function will be negative ($a
is less so "floats" to the top). If $a['id']
comes after $b['id']
then the function returns a positive number ($a
is greater so "sinks" down).
最后,使用闭包没有什么特别的理由;这只是我快速编写此类一次性函数的首选方式.它同样可以使用普通的命名函数.
Finally, there is no special reason for using a closure; it's just my go-to way of writing these sorts of throwaway functions quickly. It could equally use a normal, named function.
这篇关于按自定义顺序对数组的 php 数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!