V
V
Vasya Surname2019-03-31 18:07:00
PHP
Vasya Surname, 2019-03-31 18:07:00

How to sort a multi-dimensional array by the values ​​of another non-dimensional array?

It is necessary that the second array be sorted by the values ​​of the second
. Another difficulty is that the second array can have more keys than the first, and they must go further in order
1 array

Array
(
    [1] => B SPB
    [2] => Z SPZ
    [3] => A SPA
    [4] => C SPC
)

2 array
Array
(
    [A SPA] => Array
        (
            [title] => A SPA
            [resources] => Array
                (
                    [208] => 208
                )
        )

    [B SPB] => Array
        (
            [title] => B SPB
            [resources] => Array
                (
                    [232] => 232
                )
        )

    [C SPC] => Array
        (
            [title] => C SPC
            [resources] => Array
                (
                    [257] => 257
                )
        )

    [HTD] => Array
        (
            [title] => HTD
            [resources] => Array
                (
                    [277] => 277
                )
        )
        
    [Z SPZ] => Array
        (
            [title] => Z SPZ
            [resources] => Array
                (
                    [188] => 188
                )
        )
)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Samsonov, 2019-03-31
@bazilio2010

You need to iterate over the first array, get the value from the second, add it to the resulting array, and unset this value in the second. After iterating through all the values ​​of the first array, merge the result (array_merge) with what is left in the second array

$resultArray = [];
foreach ($firstArray as $key) {
    if (isset($secondArray[$key])) {
        $resultArray[$key] = $secondArray[$key];
        unset($secondArray[$key]);
    }
}

$resultArray = array_merge($resultArray, $secondArray);

UPDATE checked and
fixed sandbox.onlinephpfunctions.com/code/cc9e81e851d84c...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question