I'd like to sort an array with values that may or not exist in the database and the order structure should be respected.
Structure by default (positions from 1 to 5):
Amazon | Google | Ebay | Microsoft | Alibaba
This structure is initialized in PHP this way:
$data =
[
'Amazon' => ['position' => null],
'Google' => ['position' => null],
'Ebay' => ['position' => null],
'Microsoft' => ['position' => null],
'Alibaba' => ['position' => null]
];
Important: The positions stored in the database are always equal or bigger than 1.
Lets say Google has the position 1 and Alibaba 4 in the database:
$data['Google']['position'] = $fromDb->google->position; // 1
$data['Alibaba']['position'] = $fromDb->alibaba->position; // 4
If I sort the array using the array_multisort function as follows:
$sort = [];
foreach ($data as $key => $value)
$sort[$key] = $value['position'];
array_multisort($sort, SORT_ASC, $data);
Output:
Array
(
[Amazon] =>
[Ebay] =>
[Microsoft] =>
[Google] => 1
[Alibaba] => 4
)
Desired output:
Array
(
[Google] => 1
[Amazon] => 2
[Ebay] => 3
[Alibaba] => 4
[Microsoft] => 5
)