Sort multidimensional array by multiple keys

前端 未结 7 621
挽巷
挽巷 2020-11-22 10:05

I\'m trying to sort a multidimensional array by multiple keys, and I have no idea where to start. I looked at uasort, but wasn\'t quite sure how to write a function for what

相关标签:
7条回答
  • 2020-11-22 10:35

    Improving on @Stijn Leenknegt's genius code, here is my 2 cent pragmatic function:

    $data[] = array('volume' => 67, 'edition' => 2);
    $data[] = array('volume' => 86, 'edition' => 1);
    $data[] = array('volume' => 85, 'edition' => 6);
    $data[] = array('volume' => 98, 'edition' => 2);
    $data[] = array('volume' => 86, 'edition' => 6);
    $data[] = array('volume' => 67, 'edition' => 7);
    
    function make_cmp(array $sortValues)
    {
        return function ($a, $b) use (&$sortValues) {
            foreach ($sortValues as $column => $sortDir) {
                $diff = strcmp($a[$column], $b[$column]);
                if ($diff !== 0) {
                    if ('asc' === $sortDir) {
                        return $diff;
                    }
                    return $diff * -1;
                }
            }
            return 0;
        };
    }
    
    usort($data, make_cmp(['volume' => "desc", 'edition' => "asc"]));
    
    0 讨论(0)
提交回复
热议问题