【问题标题】:How to retain specific keys in array in PHP?如何在 PHP 中保留数组中的特定键?
【发布时间】:2017-05-05 08:43:17
【问题描述】:

我有一个关联数组

$preans[$id]...

其中有很多数据,关联$id

我还有另一个数组,它有

$affected_feature_ids[$id] = TRUE;

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

怎么做?

【问题讨论】:

    标签: php arrays intersection hashset


    【解决方案1】:

    你可以简单地使用array_intersect_key:

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

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

    【讨论】:

    • 别再优雅了
    【解决方案2】:

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

    $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]

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

    【讨论】:

      猜你喜欢
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 1970-01-01
      • 2015-09-06
      • 2012-01-02
      • 2014-03-21
      相关资源
      最近更新 更多