Sort an Array by keys based on another Array?

后端 未结 15 828
甜味超标
甜味超标 2020-11-22 03:29

Is it possible in PHP to do something like this? How would you go about writing a function? Here is an example. The order is the most important thing.

$custo         


        
相关标签:
15条回答
  • 2020-11-22 04:00

    Without magic...

    $array=array(28=>c,4=>b,5=>a);
    $seq=array(5,4,28);    
    SortByKeyList($array,$seq) result: array(5=>a,4=>b,28=>c);
    
    function sortByKeyList($array,$seq){
        $ret=array();
        if(empty($array) || empty($seq)) return false;
        foreach($seq as $key){$ret[$key]=$dataset[$key];}
        return $ret;
    }
    
    0 讨论(0)
  • 2020-11-22 04:01

    A bit late, but I couldn't find the way I implemented it, this version needs closure, php>=5.3, but could be altered not to:

    $customer['address'] = '123 fake st';
    $customer['name'] = 'Tim';
    $customer['dob'] = '12/08/1986';
    $customer['dontSortMe'] = 'this value doesnt need to be sorted';
    
    $order = array('name', 'dob', 'address');
    
    $keys= array_flip($order);
    uksort($customer, function($a, $b)use($keys){
        return $keys[$a] - $keys[$b];
    });
    print_r($customer);
    

    Of course 'dontSortMe' needs to be sorted out, and may appear first in the example

    0 讨论(0)
  • 2020-11-22 04:04

    I used the Darkwaltz4's solution but used array_fill_keys instead of array_flip, to fill with NULL if a key is not set in $array.

    $properOrderedArray = array_replace(array_fill_keys($keys, null), $array);
    
    0 讨论(0)
提交回复
热议问题