通过usort对多维数组进行排序

问题描述 投票:0回答:2

我想创建通用函数来排序多维数组。例如:我有这个数组

$arr = [
    [
        'product' => [
            'id' => 32,
        ],
        'price' => 23.8,
    ],
    [
        'product' => [
            'id' => 2,
        ],
        'price' => 150,
    ],
];

我需要按qazxsw poi排序。我想使用类似的东西:qazxsw poi

你能提供一些我能做到的建议吗?

php multidimensional-array usort
2个回答
0
投票

其中的关键部分是编写一个访问器函数,该函数从数据中获取单行,并以点符号形式显示“路径”,例如: $arr[0]['product']['id']

usort($arr, sortArray('product.id', 'desc'));

这会在路径的每一步中更深入地迭代到数组中,并在最后解析为值。它适用于任意数量的步骤,例如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


0
投票

usort($array, function ($a, $b) use ($field, $accessor) { $aVal = $accessor($a, $field); $bVal = $accessor($b, $field); return $aVal <=> $bVal; }); 更改为:

https://3v4l.org/UciGc

DESC更改为:

return $a['product']['id'] - $b['product']['id'];

试试这段代码:

ASC

预期产量:

return $b['product']['id'] - $a['product']['id'];
© www.soinside.com 2019 - 2024. All rights reserved.