Sort an Array by keys based on another Array?

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

    PHP has functions to help you with this:

    $arrayToBeSorted = array('west', 'east', 'south', 'north');
    $order = array('north', 'south', 'east', 'west');
    
    // sort array
    usort($arrayToBeSorted, function($a, $b) use ($order){
        // sort using the numeric index of the second array
        $valA = array_search($a, $order);
        $valB = array_search($b, $order);
    
        // move items that don't match to end
        if ($valA === false)
            return -1;
        if ($valB === false)
            return 0;
    
        if ($valA > $valB)
            return 1;
        if ($valA < $valB)
            return -1;
        return 0;
    });
    

    Usort does all the work for you and array_search provides the keys. array_search() returns false when it can't find a match so items that are not in the sort array naturally move to the bottom of the array.

    Note: uasort() will order the array without affecting the key => value relationships.

提交回复
热议问题