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.
2
Answers
You could step through original array, and check each element against your sort array:
Assumptions:
For swift checking if a given row exists in the sorting subset, populate a lookup array.
If an encountered tabelle_mannschaft value exists in the lookup array replace the current row with the first row in the subset.
There are edge cases that may cause breakage (such as duplicated values), but the sample data does not indicate the possibility of non-unique tabelle_mannschaft values.
Code: (Demo)
Or you can write to each row with the null coalescing operator if the subset can be trusted to hold the correct/full row data. (Demo)