如何检查数组的元素是否存在于另一个数组中

时间:2018-11-28 13:12:12

标签: php arrays multidimensional-array php-7

$result = array();
    $A= Array
   (
    [0] => Array
       (
        [id] => 1946
        [name] => cook
        [pic] => cookpic.png
       )

)
$B =  Array
 (
   [0] => Array
    (
        [id] => 1944
        [name] => driver
        [pic] => driver.png

    )

  [1] => Array
    (
        [id] => 934
        [name] => developer
        [pic] => developer.jpg
    )

[2] => Array
    (
        [id] => 1946
        [name] => cook
        [pic] => cookpic.png

    )

 )

我尝试过的事情:

   $result = !empty(array_intersect($a, $b));

我有两个数组,我用var_dump来显示它们,并且可以在上面看到它们。

我想要实现的是,我想比较两个职业,并希望$result数组将是唯一的。现在,如果$ B中不存在Cook,则该Cook应该以{{1​​}}数组的形式被推送,它将变成$B,否则就不应该被推送。

2 个答案:

答案 0 :(得分:1)

$result = !empty(array_intersect($a, $b));只会告诉您$a$b之间是否有共同的元素

$result = array();
$a = array(
    array(
        "id" => 1946,
        "name" => "Cook", // upper case C
        "pic" => "cookpic.png"
    ),

    array(
        "id" => 1946,
        "name" => "cook", // lower case c
        "pic" => "cookpic.png"
    )
);

$b = array(
    array(
        "id" => 1944,
        "name" => "driver",
        "pic" => "driver.png"
    ),
    array(
        "id" => 934,
        "name" => "developer",
        "pic" => "developer.png"
    ),
    array(
        "id" => 1946,
        "name" => "cook", // lower case c
        "pic" => "cookpic.png"
    )
);

foreach ($a as $k => $v) {
    if (in_array($v, $b) == false) {
        array_push($result, $v);
    }
}

print_r($result);

您可以使用array_diff,但不适用于多维数组。所以你必须从头开始

编辑:

$result = array();
$a = array(
    array(
        "id" => 1946,
        "name" => "Cook", // upper case C
        "pic" => "cookpic.png"
    ),

    array(
        "id" => 1946,
        "name" => "cook", // lower case c
        "pic" => "cookpic.png"
    )
);

$b = array(
    array(
        "id" => 1944,
        "name" => "driver",
        "pic" => "driver.png"
    ),
    array(
        "id" => 934,
        "name" => "developer",
        "pic" => "developer.png"
    ),
    array(
        "id" => 1946,
        "name" => "cook", // lower case c
        "pic" => "cookpic.png"
    )
);

$m = array_merge($a, $b);
$result = array_map("unserialize", array_unique(array_map("serialize", $m)));
print_r($result);

合并两个数组,然后使用array_map应用array_unique删除重复项

答案 1 :(得分:0)

使用strcasecmp()内置函数进行比较。然后使用array_push()。 您可以使用蛮力法。但我相信您可以从中得到更好的答案。

$result=array();
$A[0]=array("id" => 1946, "name" => Cook, "pic" => cookpic.png);
$B[0]=array("id" => 1944, "name" => driver, "pic" => driver.png);
$B[1]=array("id" => 934, "name" => developer, "pic" => developer.jpg);
$B[2]=array("id" => 1946, "name" => cook, "pic" => cookpic.png);


foreach ($A as $key => $value) 
{
    foreach ($B as $key1 => $value1) 
    {
        if (!strcasecmp($value["name"], $value1["name"])) 
        {   array_push($result, $value);    }
    }
}

echo("<pre>");print_r($result);