Home > Blockchain >  Bring sorting of a new array back into an original array
Bring sorting of a new array back into an original 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 bring the order from the array with the new order into the original array?

Original Array:

Array
(
    [0] => Array
        (
            [tabelle_mannschaft] => SV Winter
        )

    [1] => Array
        (
            [tabelle_mannschaft] => Mannschaft 7
        )

    [2] => Array
        (
            [tabelle_mannschaft] => TSV HORIZONT
        )

    [3] => Array
        (
            [tabelle_mannschaft] => Mannschaft 8
        )

)

Array with new order:

Array
        (
            [0] => Array
                (
                    [tabelle_mannschaft] => TSV HORIZONT
                )

            [1] => Array
                (
                    [tabelle_mannschaft] => Mannschaft 7
                )

        )

)

So in the case above as result I need the original array but [1] and [2] switched. Both arrays can contain much more then 2 or 3 entries. Any ideas how i can approach this?

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
  • Related