Sort an Array by keys based on another Array?

后端 未结 15 1003
甜味超标
甜味超标 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条回答
  •  萌比男神i
    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

提交回复
热议问题