如何在PHP中保留数组中的特定键?

时间:2021-03-24 10:49:08

I have an associative array

我有一个关联数组

$preans[$id]...

which has a lot of data, associated with $id.

它有很多数据,与$ id相关联。

Also I have another array, which has

我还有另一个阵列

$affected_feature_ids[$id] = TRUE;

Now I want to retain in $preans only those indexes, which exist in $affected_feature_ids.

现在我想在$ preans中只保留那些存在于$ affected_feature_ids中的索引。

How to do that?

怎么做?

2 个解决方案

#1


5  

You can simply use array_intersect_key:

你可以简单地使用array_intersect_key:

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

array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.

array_intersect_key()返回一个数组,其中包含array1的所有条目,其中包含所有参数中都存在的键。

#2


3  

Quick and inelegant working solution:

快速而不雅的工作解决方案:

$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

One more elegant solution could be:

一个更优雅的解决方案可能是:

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

The difference with Mathei Mihai answer is that it will ignore $affected_feature_ids elements where $id is false or null. In your case it will only consider $affected_feature_ids[$id] when it's true

与Mathei Mihai的不同之处在于它会忽略$ affected_feature_ids元素,其中$ id为false或null。在你的情况下,它只会考虑$ affected_feature_ids [$ id]

Now you can search for more elegant solutions!

现在您可以搜索更优雅的解决方案!

#1


5  

You can simply use array_intersect_key:

你可以简单地使用array_intersect_key:

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

array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.

array_intersect_key()返回一个数组,其中包含array1的所有条目,其中包含所有参数中都存在的键。

#2


3  

Quick and inelegant working solution:

快速而不雅的工作解决方案:

$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

One more elegant solution could be:

一个更优雅的解决方案可能是:

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

The difference with Mathei Mihai answer is that it will ignore $affected_feature_ids elements where $id is false or null. In your case it will only consider $affected_feature_ids[$id] when it's true

与Mathei Mihai的不同之处在于它会忽略$ affected_feature_ids元素,其中$ id为false或null。在你的情况下,它只会考虑$ affected_feature_ids [$ id]

Now you can search for more elegant solutions!

现在您可以搜索更优雅的解决方案!