2017-05-05 89 views
0

我有一個關聯數組如何在PHP中保留數組中的特定鍵?

$preans[$id]... 

其具有大量的數據,與$id相關聯。

我也有另一個數組,其中有

$affected_feature_ids[$id] = TRUE; 

現在我想在$preans只保留那些指標,它存在於$affected_feature_ids

如何做到這一點?

回答

3

快速和不雅工作的解決方案:

$a = [] 
foreach($affected_feature_ids as $key => $value) { 
    if ($value) $a[$key] = $preans[$key]; 
} 
// Now $a has only the elements you wanted. 
print_r($a); // <-- displays what you are asking for 

一個更優雅的解決方案可能是:

$preans = array_intersect_key($preans, array_filter($affected_feature_ids)); 

與Mathei米哈伊答案不同的是,它會忽略$affected_feature_ids元素,其中$id是虛假或無效。在你的情況下,它只會考慮$affected_feature_ids[$id]當它是true

現在你可以搜索更多的優雅的解決方案!

5

可以簡單地使用array_intersect_key

$preans = array_intersect_key($preans, $affected_feature_ids); 

array_intersect_key()返回包含具有存在於所有參數鍵ARRAY1的所有條目的陣列。

+0

不會比這更優雅 – DevDonkey

相關問題