Sort Multi-dimensional Array by given indexes - PHP?

前端 未结 3 800
我寻月下人不归
我寻月下人不归 2021-01-24 21:29

I have two array $days_order and $mysql_result, I want to sort $mysql_result array using $days_order array. I want to display

相关标签:
3条回答
  • 2021-01-24 22:00

    I did this using following script:

    function sort_array_custom_compare($mysql_result,$days_order)
        {
        uasort($mysql_result, function($a,$b) use ($days_order){
            foreach($days_order as $value){
                if($a['day'] == $value){
                    return 0;
                    break;
                }
                if($b['day'] == $value){
                    return 1;
                    break;
                }
            }
        });
        return $mysql_result;
        }
    
    0 讨论(0)
  • 2021-01-24 22:01

    You can use the custom order array in the comparison function of usort like this:

    usort($mysql_result, function ($a, $b) use ($days_order) {
        // Then check the position of the 'day' value of each element 
        // against the position of that value in $days_order.
        $a = array_search($a['day'], $days_order);
        $b = array_search($b['day'], $days_order);
        if ($a < $b) return -1;
        if ($a == $b) return 0;
        return 1;
    });
    

    If you want to do it in MySQL, for just shifting the days forward like this you could use

    ORDER BY (`day` + 1) % 7
    

    Or if it needs to be more complex than just shifting a day you can use CASE to provide a specific order (although this CASE just does the same thing):

    ORDER BY 
    CASE 
        WHEN `day` = 2 THEN 0
        WHEN `day` = 3 THEN 1
        WHEN `day` = 4 THEN 2
        WHEN `day` = 5 THEN 3
        WHEN `day` = 6 THEN 4
        WHEN `day` = 7 THEN 5
        WHEN `day` = 1 THEN 6
    END;
    
    0 讨论(0)
  • 2021-01-24 22:08

    Use usort with a custom compare function.

    Something like:

    usort($ranked, function($a, $b) {
        if ($a['day'] === $b['day']) return 0;
    
        return ($a['day'] > $b['day']) ? -1 : 1;
    });
    

    You can read more about this function here.

    0 讨论(0)
提交回复
热议问题