简体   繁体   English

按usort排序多维数组

[英]Sort multidimensional array by usort

I want to create universal function to sort multidimensional array. 我想创建通用函数来对多维数组进行排序。 For example: I have this array 例如:我有这个数组

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

And I need to sort by $arr[0]['product']['id'] . 我需要按$arr[0]['product']['id']进行排序。 I want to use sort smthg like that: usort($arr, sortArray('product.id', 'desc')); 我想使用像这样的排序smthg: usort($arr, sortArray('product.id', 'desc'));

Could you provide some idea how I can do it? 您能提供一些想法我该怎么做吗?

change for DESC as: DESC更改为:

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

change for ASC as: ASC更改为:

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

try this code: 试试这个代码:

 <?php
$arrrrr = [
    [
        'product' => [
            'id' => 32,
        ],
        'price' => 23.8,
    ],
    [
        'product' => [
            'id' => 2,
        ],
        'price' => 150,
    ],
];


$args = array('product.id','asc');//define an array of args
usort($arrrrr, function($a, $b) use ($args) {
    $firstVal = explode(".",$args[0]);
    if($args[1]=='desc'){
    return $a[$firstVal[0]][$firstVal[1]] - $b[$firstVal[0]][$firstVal[1]];
    }else{
    return $b[$firstVal[0]][$firstVal[1]] - $a[$firstVal[0]][$firstVal[1]];
    }

});


echo '<pre>';print_r($arrrrr);echo '</pre>';
?>

expected output: 预期输出:

Array
(
    [0] => Array
        (
            [product] => Array
                (
                    [id] => 2
                )

            [price] => 150
        )

    [1] => Array
        (
            [product] => Array
                (
                    [id] => 32
                )

            [price] => 23.8
        )

)

The critical part of this is to write an accessor function that takes a single row from your data along with a "path" in dot-notation, eg rating.top . 关键是编写一个访问器函数,该函数将从数据中获取一行并以点符号表示“ path”,例如rating.top

$accessor = function($row, $path) {
    $steps = explode('.', $path);

    $return = $row[array_shift($steps)];

    while ($level = array_shift($steps)) {
        $return =& $return[$level];
    }

    return $return;
};

This iterates deeper into the array with each step of the path, and resolves to the value at the end. 这会在路径的每一步中更深入地遍历数组,并解析为最后的值。 It'll work for an arbitrary number of steps, eg user.rating.top.foo.var.whatever . 它适用于任意数量的步骤,例如user.rating.top.foo.var.whatever It's essentially a very cut-down version of Symfony's PropertyAccess component . 它本质上是Symfony的PropertyAccess组件的简化版本。

Using this, you can construct a callback to pass to usort that will compare the accessed values from the two elements being compared. 使用此方法,您可以构造一个传递给usort的回调,该回调将比较来自两个被比较元素的访问值。

usort($array, function ($a, $b) use ($field, $accessor) {
    $aVal = $accessor($a, $field);
    $bVal = $accessor($b, $field);

    return $aVal <=> $bVal;
});

You can see a fully worked version here: https://3v4l.org/UciGc 您可以在这里看到完整的版本: https : //3v4l.org/UciGc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM