How can you handle sorting and filtering data based on availability and price in PHP?
To handle sorting and filtering data based on availability and price in PHP, you can use array functions like `array_filter()` and `usort()`. First, filter the data based on availability using `array_filter()`, then sort the filtered data based on price using `usort()`. This approach allows you to efficiently manipulate and display the data according to availability and price criteria.
// Sample data array
$data = [
['name' => 'Product A', 'availability' => true, 'price' => 50],
['name' => 'Product B', 'availability' => false, 'price' => 30],
['name' => 'Product C', 'availability' => true, 'price' => 40],
];
// Filter data based on availability
$availableData = array_filter($data, function($item) {
return $item['availability'] === true;
});
// Sort filtered data based on price
usort($availableData, function($a, $b) {
return $a['price'] <=> $b['price'];
});
// Output sorted and filtered data
foreach ($availableData as $item) {
echo $item['name'] . ' - Price: $' . $item['price'] . PHP_EOL;
}
Keywords
Related Questions
- What are some alternative methods to accurately count words in a string in PHP, especially when dealing with special characters?
- What are the advantages of using IntlDateFormatter over traditional PHP methods for displaying weekdays?
- What are the best practices for handling variables in PHP scripts without relying on register_globals?