PHP - Sort array elements based on another array's elements :)

前端 未结 1 1605
傲寒
傲寒 2021-01-19 10:54

so I have two arrays. one of them looks like this (it\'s values or the number of elements can change):

array(\'4dec\' , \'def3\', \'a3d6\', \'d12f\');


        
相关标签:
1条回答
  • 2021-01-19 11:09

    Stability was a twist, as PHP doesn't respect that any longer, but a little extra work keeps the sort stable.

    $order_by = array('4dec' , 'def3', 'a3d6', 'd12f');
    
    $data = array(array('id' => 'd12f', 'name' => 'John'),
                  array('id' => 'a5f1', 'name' => 'Kathy'),
                  array('id' => 'def3', 'name' => 'Jane'),
                  array('id' => 'a3d6', 'name' => 'Amy'),
                  array('id' => '4dec', 'name' => 'Mary'),      
                  array('id' => 'ecc2', 'name' => 'Fred'));
    
    // create a lookup table for sorted order to avoid repeated searches
    $order_index = array_flip($order_by);
    
    // create a lookup table for original order: in PHP 4.1.0 usort became unstable
    // http://www.php.net/manual/en/function.usort.php
    $orig_order_by = array_map(function($a){return $a['id'];}, $data);
    $orig_index = array_flip($orig_order_by);
    
    // sort values by specified order, with stability
    $compare = function($a, $b) use (&$order_index, &$orig_index) {
        $aid = $a['id'];
        $bid = $b['id'];
    
        $ai = $order_index[$aid];
        $bi = $order_index[$bid];
    
        if ($ai === null and $bi === null) { // original sort order for stability
            return $orig_index[$aid] - $orig_index[$bid];
        }
        if ($ai === null) { return 1; }
        if ($bi === null) { return -1; }
    
        return $ai - $bi;
    };
    usort($data, $compare);
    var_dump($data);
    
    0 讨论(0)
提交回复
热议问题