Home > database >  Rearrange original 2d array items which are nominated in another 2d array
Rearrange original 2d array items which are nominated in another 2d array

Time:11-05

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.

CodePudding user response:

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

CodePudding user response:

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)

$lookup = array_column($subset, 'tabelle_mannschaft', 'tabelle_mannschaft');
foreach ($array as $i => $row) {
    if (isset($lookup[$row['tabelle_mannschaft']])) {
        $array[$i] = array_shift($subset);
    }
}
var_export($array);

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)

$lookup = array_column($subset, null, 'tabelle_mannschaft');
foreach ($array as &$row) {
    $row = $lookup[$row['tabelle_mannschaft']] ?? array_shift($subset);
}
var_export($array);
  • Related