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 recommended PHP configuration settings for session management to prevent issues with session data loss or inconsistency when using a custom session handler?
- What are the potential legal implications of using external news feeds on a website for SEO purposes?
- How can PHP developers ensure smooth database connections and data retrieval for dynamic content like polls or surveys?