Sort Multi-dimensional Array by given indexes - PH

2020-04-24 16:57发布

问题:

I have two array $days_order and $mysql_result, I want to sort $mysql_result array using $days_order array. I want to display MySQL result in days order ascending? Is there any way to do this or any other way so that I can pass $days_order in MySQL query in OrderBy section?

$days_order =  Array([0] => 2[1] => 3[2] => 4[3] => 5 [4] => 6[5] => 7[6] => 1);

$mysql_result = Array (

    [0] => Array
        (
            [hashtag] => a7e87329b5eab8578f4f1098a152d6f4
            [title] => Flower
            [day] => 3
        )

[1] => Array
    (
        [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
        [title] => Free
        [day] => 2
    )

[2] => Array
    (
        [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
        [title] => Ready
        [day] => 1
    )
)

I want sorted array in $days_order

Output:

  Array
(
  [0] => Array
    (
           [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
           [title] => Free
           [day] => 2
    )
  [1] => Array
        (
            [hashtag] => a7e87329b5eab8578f4f1098a152d6f4
            [title] => Flower
            [day] => 3
        )

  [2] => Array
    (
           [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
           [title] => Ready
           [day] => 1
    )    
)

回答1:

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.



回答2:

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;
    }


回答3:

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;