array_intersect_ukey(array $array1, array $array2, callable $key_compare_func): array
This function returns an array that contains all the keys in $array1 that also exist in $array2 . The comparison method of keys is determined by key_compare_func .
array_keys(array $array, mixed $search_value = null, bool $strict = false): array
array_keys returns all keys in the array, or, in the case of a specified value, returns the key corresponding to the value.
Imagine that when we process data returned by a set of APIs, we need to filter out the specified fields from multiple return fields for further processing, such as logging or presenting to the front-end. Here is a typical scenario.
$apiData = [
'id' => 101,
'username' => 'alice',
'email' => '[email protected]',
'status' => 'active',
'created_at' => '2024-06-01 12:00:00',
'updated_at' => '2024-06-10 08:30:00'
];
$logFields = ['id', 'username', 'email'];
We want to keep only the contents with the $apiData keys 'id' , 'username' and 'email' and discard other fields.
$allowedKeys = array_flip($logFields);
$filteredData = array_intersect_ukey(
$apiData,
$allowedKeys,
function ($key1, $key2) {
return strcmp($key1, $key2);
}
);
Array
(
[id] => 101
[username] => alice
[email] => [email protected]
)
array_flip($logFields) flips the array of key names we need to be an array whose key name is field name and value is indexed, so that it can be used as a comparison object for array_intersect_ukey .
Use strcmp as a comparison function to implement standard string comparison.
The final result is the set of fields in which the $apiData key exists in $logFields .
Suppose we are dealing with a set of user configuration data with URLs, we want to keep only the portion containing the whitelisted URL domain name.
$userSettings = [
'homepage' => 'https://gitbox.net/home',
'avatar' => 'https://cdn.gitbox.net/avatar.jpg',
'backup_site' => 'https://example.com/backup',
'profile' => 'https://gitbox.net/user/profile'
];
$validUrls = array_keys(
array_filter($userSettings, function ($url) {
return parse_url($url, PHP_URL_HOST) === 'gitbox.net';
})
);
$validKeys = array_flip($validUrls);
$filteredSettings = array_intersect_ukey(
$userSettings,
$validKeys,
'strcmp'
);
print_r($filteredSettings);
Array
(
[homepage] => https://gitbox.net/home
[profile] => https://gitbox.net/user/profile
)
First filter the main domain name of the URL in the value through array_filter .
array_keys extracts the key names that meet the requirements.
Then filter out the data through array_flip and array_intersect_ukey .
This method allows us to preserve the corresponding keys in the array according to some logic in the value , thus performing very flexible structured data processing.