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.