0

I want to usort an multi-dimension array by an array so that the order of id in multi-dimension array will be arranged in order the I want. Besides, my multi-dimension array will contain values that does not in the array which is one of the reason give me headache as the usort will not works as usual.

my multi-dimension array:

$sortme = Array (
  [10005] => Array //this is the id and my expected order will be (10003,10002,10005)
        (        
          [odds] => Array
            (
               [a] => Array
                   (
                     [oda] => 1.230
                     [odb] => 0.650
                   )
                )
            )
   [10002] => Array
        (        
          [odds] => Array
            (
               [a] => Array
                   (
                     [oda] => 2.0
                     [odb] => 3.0
                   )
                )
         )
   [10003] => Array
        (        
          [odds] => Array
            (
               [a] => Array
                   (
                     [oda] => 4.0
                     [odb] => 5.0
                   )
                )
         )
   [20005] => Array  //extra id
        (        
          [odds] => Array
            (
               [a] => Array
                   (
                     [oda] => 4.0
                     [odb] => 5.0
                   )
                )
         )
 )

follow by this array:

$correct = Array ( [0] => 10003 [1] => 10002 [2] => 10005)

I have tried : but this does not work on multi-dimension array as the result before and after is the same.

foreach ($sortme as $key => $value) {
    $sortmee[$key]=$key;

    $sort = function ($a, $b) use ($correct ) {
           return array_search($a, $correct ) - array_search($b, $correct );
        };
   usort($sortmee[$key], $sort);
 }


C123D
  • 51
  • 5
  • Surely [`ksort`](https://3v4l.org/tv5UU) is enough to solve this? If I am not mistaken, you want the keys sorting in ascedening order? – Jaquarh Jan 16 '23 at 08:31
  • neither ascending nor descending order, the order of id is random so it need to follow the array – C123D Jan 16 '23 at 08:35
  • We already have custom sorting php pages here. This page should be closed instead of answered. Such as [How can I custom sort php array with uasort?](https://stackoverflow.com/q/40868637/2943403) – mickmackusa Jan 16 '23 at 08:40
  • 1
    In the dupe target, simply change `usort()` to `uksort()` because you want to sort keys. – mickmackusa Jan 16 '23 at 08:45

0 Answers0