array_intersect_ukey(array $array1, array $array2, callable $key_compare_func): array
此函數返回一個數組,該數組包含了$array1中所有鍵也存在於$array2中的元素,鍵的比較方式由key_compare_func決定。
array_keys(array $array, mixed $search_value = null, bool $strict = false): array
array_keys返回數組中所有的鍵,或者在指定值的情況下,返回與該值對應的鍵。
設想我們在處理一組API 返回的數據時,需要從多個返回字段中篩選出指定的字段進行進一步的處理,比如日誌記錄或展示給前端。以下是一個典型場景。
$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'];
我們希望只保留$apiData中鍵為'id' 、 'username'和'email'的內容,並丟棄其他字段。
$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)將我們需要的鍵名數組翻轉為鍵名是字段名、值為索引的數組,這樣就可以用作array_intersect_ukey的比較對象。
使用strcmp作為比較函數,實現標準的字符串比較。
最終結果即為$apiData中鍵存在於$logFields的字段集合。
假設我們處理的是一組帶有URL 的用戶配置數據,我們想只保留包含白名單URL 域名的部分。
$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
)
先通過array_filter對值中URL 的主域名進行篩選。
array_keys提取符合要求的鍵名。
再通過array_flip和array_intersect_ukey將數據篩選出來。
這種方式讓我們可以根據值中的某些邏輯來保留數組中對應的鍵,從而進行非常靈活的結構化數據處理。