0

I'm using array_multisort like always, but this time it does have trouble sorting correctly.

I use it to sort a multidimensional array ($data), but I simplified the problem in this example:

    $data = array(6 => 'WEEK 48', 7 => 'WEEK 49', 8 => 'WEEK 47', 9 => 'WEEK 50', 10 => 'WEEK 51');

    $sort = array(8 => 201647, 6 => 201648, 7 => 201649, 9 => 201650, 10 => 201651);

    array_multisort($sort, SORT_ASC, $data);

    Output:
    Array
    (
        [0] => WEEK 48
        [1] => WEEK 49
        [2] => WEEK 47
        [3] => WEEK 50
        [4] => WEEK 51
    )

What am I missing?

Roel Jansen
  • 306
  • 2
  • 11
  • 1
    Seems your input parameters are icorrect http://www.w3schools.com/Php/func_array_multisort.asp You are sorting $sort array instead of $data – VadimB Nov 23 '16 at 09:22

3 Answers3

1

Try this

    <?php

       $data = array(6 => 'WEEK 48', 7 => 'WEEK 49', 8 => 'WEEK 47', 9 => 'WEEK 50', 10 => 'WEEK 51');

        $sort = array(8 => 201647, 6 => 201648, 7 => 201649, 9 => 201650, 10 => 201651);

        array_multisort($data, SORT_ASC, $sort);

         echo '<pre>';
         print_r($data);

   ?>

output:

Array
(
    [0] => WEEK 47
    [1] => WEEK 48
    [2] => WEEK 49
    [3] => WEEK 50
    [4] => WEEK 51
)
Akshay
  • 700
  • 9
  • 23
Shanu k k
  • 1,235
  • 2
  • 18
  • 43
  • I need $sort to be the sorting array, because $data is in fact a multidimensional array. Why doesn't it work the other way around? – Roel Jansen Nov 23 '16 at 10:00
0

Syntax

array_multisort(array1,sorting order,sorting type,array2,array3...)

You should provide sorting_type for your array

array_multisort($sort, SORT_ASC, SORT_STRING, $data, SORT_ASC, SORT_NUMERIC);

var_dump($sort);
var_dump($data);

Results:

array(5) { 
    [0]=> int(201647) 
    [1]=> int(201648) 
    [2]=> int(201649) 
    [3]=> int(201650) 
    [4]=> int(201651) 
} 

array(5) { 
    [0]=> string(7) "WEEK 47" 
    [1]=> string(7) "WEEK 48" 
    [2]=> string(7) "WEEK 49" 
    [3]=> string(7) "WEEK 50" 
    [4]=> string(7) "WEEK 51" 
}
Doanh
  • 1
  • 3
0

Stupid me, there was a ksort($data) in between lines which screwed up the sorting.

Roel Jansen
  • 306
  • 2
  • 11