In PHP development, you often encounter the need to filter out certain key values from multi-dimensional arrays. This article will introduce how to combine the two functions array_diff() and array_keys() to achieve this function gracefully and efficiently.
array_keys()
Returns all key names in the array, supporting specified key value filtering.
array_diff()
Computes the difference between two (or more) arrays, returning values in the first array but not in other arrays.
By combining these two functions, we can first get all the key names of the array, then eliminate unnecessary keys through the difference, and finally regenerate the filtered array.
Suppose there is a multi-dimensional array with the following structure:
$data = [
[
'id' => 1,
'name' => 'Alice',
'age' => 25,
'city' => 'Beijing',
],
[
'id' => 2,
'name' => 'Bob',
'age' => 30,
'city' => 'Shanghai',
],
];
We want to filter out the age and city fields in each subarray, leaving only the id and name .
<?php
$data = [
[
'id' => 1,
'name' => 'Alice',
'age' => 25,
'city' => 'Beijing',
],
[
'id' => 2,
'name' => 'Bob',
'age' => 30,
'city' => 'Shanghai',
],
];
// Key names that need to be filtered out
$keysToRemove = ['age', 'city'];
$result = [];
foreach ($data as $item) {
// Get all keys of the current array
$keys = array_keys($item);
// Calculate the keys to be retained,Right now $keys and $keysToRemove The difference set
$filteredKeys = array_diff($keys, $keysToRemove);
// Reconstruct subarrays with reserved keys
$filteredItem = [];
foreach ($filteredKeys as $key) {
$filteredItem[$key] = $item[$key];
}
$result[] = $filteredItem;
}
print_r($result);
Get all key names of the current subarray through array_keys($item) .
Use array_diff() to calculate the key you want to keep, that is, the original key set minus the key set to be deleted.
Iterate over the filtered key names and reassemble the new array.
Finally, $result is the filtered multi-dimensional array.
Array
(
[0] => Array
(
[id] => 1
[name] => Alice
)
[1] => Array
(
[id] => 2
[name] => Bob
)
)
Through the combination of array_diff() and array_keys() , we can quickly and flexibly filter out specified key values from multidimensional arrays. This method is highly versatile and is suitable for handling various complex array structures. If there are more keys to filter or the array level is deeper, it can also be encapsulated into functions for recursive processing.