-1

Here I have 2 array. One which provides sequence that is SortedArray and second that provides only data MyArrayUnsorted

I have SortedArray as a sequence that i need to print my data that is available in MyArrayUnsorted.

Remember the values are dynamic.

SortedArray
(
    [0] => 8500
    [1] => 8501
    [2] => 8503
    [3] => 8502
)
MyArrayUnsorted
(
    [0] => array(
            myid= '8500'
           )
    [1] => array(
            myid= '8501'
           )
    [2] => array(
            myid= '8502'
           )
    [3] => array(
            myid= '8503'
           )

  )

FinalSortedArray
(
    [0] => array(
            myid= '8500'
           )
    [1] => array(
            myid= '8501'
           )
    [2] => array(
            myid= '8503'
           )
    [3] => array(
            myid= '8502'
           )

  )
bacev
  • 25
  • 5
  • 2
    Does this answer your question? [PHP-Sort array based on another array?](https://stackoverflow.com/questions/17338074/php-sort-array-based-on-another-array) – CBroe Dec 11 '20 at 14:27

1 Answers1

0

It looks pretty straightforward, you just need to array_flip the sorted array and usort the unsorted one.

<?php

declare(strict_types=1);

$sortedArray = [
    '8500',
    '8501',
    '8503',
    '8502',
];

$myArrayUnsorted = [
    [
        'myid' => '8500',
    ],
    [
        'myid' => '8501',
    ],
    [
        'myid' => '8502',
    ],
    [
        'myid' => '8503',
    ],
];

$flippedArray = array_flip($sortedArray);

usort($myArrayUnsorted, static function ($a, $b) use ($flippedArray) {
    $aIndex = $flippedArray[$a['myid']] ?? null;
    $bIndex = $flippedArray[$b['myid']] ?? null;

    return $aIndex <=> $bIndex;
});

var_dump($myArrayUnsorted);

It would give the following output.

array(4) {
  [0]=>
  array(1) {
    ["myid"]=>
    string(4) "8500"
  }
  [1]=>
  array(1) {
    ["myid"]=>
    string(4) "8501"
  }
  [2]=>
  array(1) {
    ["myid"]=>
    string(4) "8503"
  }
  [3]=>
  array(1) {
    ["myid"]=>
    string(4) "8502"
  }
}
Mikhail Prosalov
  • 4,155
  • 4
  • 29
  • 41