【问题标题】:Compare two arrays for specific data比较两个数组的特定数据
【发布时间】:2018-09-27 08:36:49
【问题描述】:

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

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"
}}

我尝试了 array_diff 和 array_intersect 但这不是我需要的结果。我也在 foreach 循环中尝试过,但我无法修复以获得我的目标。是否有一些现成的 php 函数可以得到这个?

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    要以最通用的方式实现这一点,您可以使用 array_filterarray_diffarray_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 是你想要的输出

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      相关资源
      最近更新 更多