Search code examples
phparrayssortingmultidimensional-arraylookup

Rearrange original 2d array items which are nominated in another 2d array


I have two arrays, one with the original data, and another one that contains the same entries but in a new order.

How can I sort the original array so that only items nominated in the new order array are moved?

Original Array:

[
    ['tabelle_mannschaft' => 'SV Winter'],
    ['tabelle_mannschaft' => 'Mannschaft 7'],
    ['tabelle_mannschaft' => 'TSV HORIZONT'],
    ['tabelle_mannschaft' => 'Mannschaft 8'],
]

New order array:

[
    ['tabelle_mannschaft' => 'TSV HORIZONT'],
    ['tabelle_mannschaft' => 'Mannschaft 7'],
]

So in the case above as result I need the original array but with items [1] and [2] switched.

Desired result:

[
    ['tabelle_mannschaft' => 'SV Winter'],
    ['tabelle_mannschaft' => 'TSV HORIZONT'],
    ['tabelle_mannschaft' => 'Mannschaft 7'],
    ['tabelle_mannschaft' => 'Mannschaft 8'],
]

For clarity, both arrays can contain much more then 2 or 3 entries.


Solution

  • You could step through original array, and check each element against your sort array:

    • if it's not found, move on to the next element in the original array
    • if it is found
      • if it's at the first position, remove it from the sort array, move on to the next element in the original array
      • otherwise remove the element from it's current position in the original array and append it to the end, move on to the next element in the original array

    Assumptions:

    • all the elements in the sort array appear once and once only in the original array