代码之家  ›  专栏  ›  技术社区  ›  wenus

比较两个数组中的特定数据

  •  1
  • wenus  · 技术社区  · 6 年前

    我有个小问题。我必须像这样比较数组:

    array(2) {
     [0]=>
      array(4) {
    ["persons"]=>
    int(1)
    ["date"]=>
    string(21) "2018-10-01 2018-11-14"
    ["type"]=>
    string(7) "for one"
    ["sun"]=>
    string(3) "yes"
     }
    [1]=>
     array(4) {
    ["persons"]=>
    int(2)
    ["date"]=>
    string(21) "2018-10-01 2018-10-14"
    ["type"]=>
    string(7) "for two"
    ["sun"]=>
    string(3) "yes"
    }}
    

    现在我有了一些选项,例如:

    array(2) {
    ["type"]=>
    string(7) "for two"
    ["sun"]=>
    string(3) "yes"
    

    array(1) {
    
    [0]=>
    array(2) {
    ["persons"]=>
    int(2)
    ["date"]=>
    string(21) "2018-10-01 2018-10-14"
    }}
    

    我尝试了数组diff和数组intersect,但这不是我需要的结果。我也尝试了foreach循环,但我无法修复以获得我的目标。有什么现成的php函数可以得到这个吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   dWinder Dharman    6 年前

    array_filter , array_diff array_map

    考虑以下示例:

    $a = array("a" => "aaa", "b" => "bbb", "c" => "ddd");
    $b = array("a" => "aaa", "b" => "bbb", "c" => "ccc");
    $arr = array($a,$b); // this is your base array
    
    $find = array("b" => "bbb", "c" => "ccc"); // this is as your options (what you want to find)
    

    现在你可以做:

    $barr = array_filter($arr, function($elem) use ($find) {
            return count(array_intersect($find, $elem)) == count($find);
    }); // $barr contains only the sub-arrays that contains the option you wanted
    
    
    $carr = array_map(function($elem) use ($find) {
            return array_diff($elem, $find);
    },$barr); // $carr contain only the field that are not in the option array
    

    现在 $carr 是你的欲望输出吗