What are the potential pitfalls of sorting a 2-dimensional array in PHP based on multiple criteria such as name and license plate?
When sorting a 2-dimensional array in PHP based on multiple criteria such as name and license plate, the potential pitfalls include complexity in writing custom comparison functions and ensuring that the sorting logic is correctly implemented. To solve this issue, you can use the `array_multisort()` function in PHP, which allows sorting multiple arrays or multi-dimensional arrays based on one or more related columns.
<?php
// Sample 2-dimensional array
$data = array(
array('name' => 'John', 'license_plate' => 'ABC123'),
array('name' => 'Alice', 'license_plate' => 'XYZ789'),
array('name' => 'Bob', 'license_plate' => 'DEF456')
);
// Separate the columns to be sorted
foreach ($data as $key => $row) {
$names[$key] = $row['name'];
$license_plates[$key] = $row['license_plate'];
}
// Sort the data based on multiple criteria
array_multisort($names, SORT_ASC, $license_plates, SORT_ASC, $data);
// Output the sorted array
print_r($data);
?>