Let's say I have one array of ID numbers in a desired particular order. I have a second array of objects that were sorted by an ID property from the first array.
$array1 = [3,4,2,1,5];
$array2 = [
["id" => 1, "data" => "one"],
["id" => 2, "data" => "two"],
["id" => 3, "data" => "fre"],
["id" => 4, "data" => "foe"],
["id" => 5, "data" => "fie"]
];
In PHP, what is the best way of 'unsorting' or reverting the second array to the original order of the first array?
The closest answer I can find without using a sort is:
$array1_flipped = array_flip($array1);
$array2_unsorted = array();
for($i = 0; $i < count($array1); $i++) {
$array2_unsorted[$array1_flipped[$array2[$i]['id']]] = $array2[$i];
}
return($array2_unsorted);
Edit: For those interested, here is how the question arose. The first array is a list of IDs to be displayed in a particular order. The second array is the return of the MySQL call WHERE id IN $array2
, which is returned sorted. However, the second array needs to be resorted back into the order of the first array. Due to size issues, I was hoping to be able to remap the second array using the keys and values of the first array without sorting.
I found the solution by introducing a third array and using a method similar to Gauss-Jordan elimination. While this is beautiful, I wish there was a one-step algorithm for this. I'll award the correct answer to anyone who finds it.
$array1 = [3,4,2,1,5];
$array2 = [
["id" => 1, "data" => "one"],
["id" => 2, "data" => "two"],
["id" => 3, "data" => "fre"],
["id" => 4, "data" => "foe"],
["id" => 5, "data" => "fie"]
];
// Placeholder sorted ascending array (e.g. $array3 = [1,2,3,4,5])
$array3 = range(1,count($array1));
array_multisort($array1, $array3);
// Now $array3 = [4,3,1,2,5], the inverse map of an $array1 sort
array_multisort($array3, $array2);
return $array2;