无法找到比较数组键的方法

时间:2015-08-25 11:31:01

标签: php arrays

我有两个阵列:

Array ONE
(
    [39] => Dude, Harry [10%]
    [36] => Occonell, Tim [90%]
)

Array TWO
(
    [1] => Person, Admin
    [2] => Snow, John
    [3] => Jane, Marry
    [14] => Kelchenko, Igory
    [18] => Bery, Grass
    [36] => Occonell, Tim
)

我正在尝试从第二个数组中删除值,如果它的键等于第一个数组。所以我的数组应该是这样的:

Array TWO
(
    [1] => Person, Admin
    [2] => Snow, John
    [3] => Jane, Marry
    [14] => Kelchenko, Igory
    [18] => Bery, Grass
)

我试图在其他地方找到答案,但我找不到答案。

2 个答案:

答案 0 :(得分:3)

array_diff()是正确的方向,但你想用数组的键做一些事情,所以使用:array_diff_key(),例如

print_r(array_diff_key($array2, $array1));

举个例子:

$array2 = [
    1 => "a",
    2 => "b",
    3 => "c",
    4 => "d",
    5 => "e",
]; 

$array1 = [
    2 => "Don't want this key",
    4 => "Also don't want this one",
];

输出将是:

Array ( 
    1 => a
    3 => c
    5 => e
)

答案 1 :(得分:3)

您可以执行以下操作

foreach($arr_one as $key => $val){
    if(isset($array_2[$key]))    unset($array_2[$key]);
}