How can multidimensional arrays be used to prevent data loss when sorting arrays in PHP?

When sorting arrays in PHP, data loss can occur if the keys are not preserved during the sorting process. One way to prevent this data loss is by using multidimensional arrays. By storing the data in a multidimensional array where each element contains both the original value and its corresponding key, you can sort the array based on the original values while still preserving the keys.

// Sample multidimensional array with original values and keys
$data = [
    ['key' => 1, 'value' => 'apple'],
    ['key' => 3, 'value' => 'banana'],
    ['key' => 2, 'value' => 'orange']
];

// Sort the multidimensional array based on the 'value' field
usort($data, function($a, $b) {
    return $a['value'] <=> $b['value'];
});

// Output the sorted array while preserving the original keys
foreach ($data as $item) {
    echo $item['key'] . ': ' . $item['value'] . PHP_EOL;
}