Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create sort_array_by_map #434

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions php/sort_array_by_map
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

function sortByIdsMap(array &$items, array $map): void
{
$itemsSortIdsMap = [];
foreach (array_keys($items) as $key) {
$itemsSortIdsMap[$key] = array_search($key, $map, false);
}

array_multisort($itemsSortIdsMap, $items);
}

$items = [
'SECOND_MESSAGE' => 'text message 2',
'FIRS_MESSAGE' => 'text message 1',
'THIRD_MESSAGE' => 'text message 3',
];

$map = ['FIRS_MESSAGE', 'SECOND_MESSAGE', 'THIRD_MESSAGE'];

sortByIdsMap($items, $map);

print_r($items);

/*
Array
(
[FIRS_MESSAGE] => text message 1
[SECOND_MESSAGE] => text message 2
[THIRD_MESSAGE] => text message 3
)
*/