【问题标题】:Intersect associative array from another array in php [closed]将关联数组与php中的另一个数组相交[关闭]
【发布时间】:2019-04-09 15:47:09
【问题描述】:

我有两个数组是

$a = 数组( 大批( 'id' => 1, '名字' => "脸书" ), 大批( 'id' => 2, '名字' => "推特" ), 大批( 'id' => 3, '名称' => "谷歌" ), 大批( 'id' => 4, '名称' => "Linkdin" ), 大批( 'id' => 5, '名称' => "Github" ), );

另一个是,

$b = array(1, 3, 5);

根据 $b 数组值,将选择 $a 关联数组 id 作为结果。 所以结果会是,

$结果 = $a = 数组( 大批( 'id' => 1, '名字' => "脸书" ), 大批( 'id' => 3, '名称' => "谷歌" ), 大批( 'id' => 5, '名称' => "Github" ), );

【问题讨论】:

  • 到目前为止你有没有尝试过?

标签: php arrays search intersect


【解决方案1】:

简单的 oneliner(不过 4 行更易读):

$result = array_filter(
    $a, 
    function($v) use ($b) { return in_array($v['id'], $b); }
);

【讨论】:

    【解决方案2】:
    foreach ($a as $key => $value) {
        if (in_array($value['id'], $b)) {
            $result[] = $value;
        }
    }
    

    【讨论】:

      【解决方案3】:

      另一种计算交集的方法:

      $result = array_intersect_key(array_column($a, null, 'id'), array_flip($b));
      
      • 通过id重新索引$a
      • 翻转$b 以获取值作为键
      • 计算键的交集

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-23
        • 1970-01-01
        • 2021-05-15
        • 2012-02-05
        • 1970-01-01
        相关资源
        最近更新 更多