我想创建通用函数来对多维数组进行排序。 例如:我有这个数组
$arr = [
[
'product' => [
'id' => 32,
],
'price' => 23.8,
],
[
'product' => [
'id' => 2,
],
'price' => 150,
],
];
我需要按$arr[0]['product']['id']
进行排序。我想使用像这样的排序smthg:usort($arr, sortArray('product.id', 'desc'));
您能提供一些我该怎么做的想法吗?
答案 0 :(得分:0)
其中的关键部分是编写一个访问器函数,该函数将从数据中获取一行并以点符号表示“路径”,例如rating.top
。
$accessor = function($row, $path) {
$steps = explode('.', $path);
$return = $row[array_shift($steps)];
while ($level = array_shift($steps)) {
$return =& $return[$level];
}
return $return;
};
此操作在路径的每一步中都更深入地迭代数组,并解析为最后的值。它适用于任意数量的步骤,例如user.rating.top.foo.var.whatever
。本质上,它是Symfony's PropertyAccess component的简化版本。
使用此方法,您可以构造一个回调传递给usort
,该回调将比较来自两个被比较元素的访问值。
usort($array, function ($a, $b) use ($field, $accessor) {
$aVal = $accessor($a, $field);
$bVal = $accessor($b, $field);
return $aVal <=> $bVal;
});
您可以在此处查看完整版本:https://3v4l.org/UciGc