Sort an Array by keys based on another Array?

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

    There you go:

    function sortArrayByArray(array $array, array $orderArray) {
        $ordered = array();
        foreach ($orderArray as $key) {
            if (array_key_exists($key, $array)) {
                $ordered[$key] = $array[$key];
                unset($array[$key]);
            }
        }
        return $ordered + $array;
    }
    

提交回复
热议问题