2017-05-05 82 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

相关问题