【发布时间】:2017-05-05 08:43:17
【问题描述】:
我有一个关联数组
$preans[$id]...
其中有很多数据,关联$id。
我还有另一个数组,它有
$affected_feature_ids[$id] = TRUE;
现在我只想在$preans 中保留那些存在于$affected_feature_ids 中的索引。
怎么做?
【问题讨论】:
标签: php arrays intersection hashset
我有一个关联数组
$preans[$id]...
其中有很多数据,关联$id。
我还有另一个数组,它有
$affected_feature_ids[$id] = TRUE;
现在我只想在$preans 中保留那些存在于$affected_feature_ids 中的索引。
怎么做?
【问题讨论】:
标签: php arrays intersection hashset
你可以简单地使用array_intersect_key:
$preans = array_intersect_key($preans, $affected_feature_ids);
array_intersect_key() 返回一个数组,其中包含 array1 的所有条目,这些条目的键出现在所有参数中。
【讨论】:
快速而不优雅的工作解决方案:
$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 Mihai 答案的不同之处在于它将忽略 $affected_feature_ids 元素,其中 $id 为 false 或 null。在您的情况下,它只会在 true 时考虑 $affected_feature_ids[$id]
现在您可以搜索更优雅的解决方案!
【讨论】: