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
- How can one troubleshoot and debug PHP scripts that are not producing error messages when interacting with a MySQL database?
- What are the potential pitfalls of using is_int() to check the type of variables fetched from a MySQL database in PHP?
- How can the number_format function be used to format a variable within an echo statement in PHP?