Sort an Array by keys based on another Array?

后端 未结 15 834
甜味超标
甜味超标 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 03:40

    How about this solution

    $order = array(1,5,2,4,3,6);
    
    $array = array(
        1 => 'one',
        2 => 'two',
        3 => 'three',
        4 => 'four',
        5 => 'five',
        6 => 'six'
    );
    
    uksort($array, function($key1, $key2) use ($order) {
        return (array_search($key1, $order) > array_search($key2, $order));
    });
    

提交回复
热议问题