Sort an Array by keys based on another Array?

后端 未结 15 1119
甜味超标
甜味超标 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:46

    This function return a sub and sorted array based in second parameter $keys

    function array_sub_sort(array $values, array $keys){
        $keys = array_flip($keys);
        return array_merge(array_intersect_key($keys, $values), array_intersect_key($values, $keys));
    }
    

    Example:

    $array_complete = [
        'a' => 1,
        'c' => 3,
        'd' => 4,
        'e' => 5,
        'b' => 2
    ];
    
    $array_sub_sorted = array_sub_sort($array_complete, ['a', 'b', 'c']);//return ['a' => 1, 'b' => 2, 'c' => 3];
    

提交回复
热议问题