What are some methods for filtering subarrays in a multidimensional array based on specific key/value pairs in PHP?
When working with multidimensional arrays in PHP, you may need to filter subarrays based on specific key/value pairs. One way to achieve this is by using the array_filter() function along with a custom callback function that checks for the desired key/value pair in each subarray. This allows you to selectively include or exclude subarrays based on your criteria.
// Sample multidimensional array
$users = [
['id' => 1, 'name' => 'Alice', 'age' => 25],
['id' => 2, 'name' => 'Bob', 'age' => 30],
['id' => 3, 'name' => 'Charlie', 'age' => 28]
];
// Filter subarrays based on age less than 30
$filteredUsers = array_filter($users, function($user) {
return $user['age'] < 30;
});
// Output the filtered subarrays
print_r($filteredUsers);