Sort Multi-dimensional Array by given indexes - PHP?

前端 未结 3 803
我寻月下人不归
我寻月下人不归 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: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;
    

提交回复
热议问题