如果key在另一个数组中,则从数组中删除键

时间:2022-04-01 01:45:50

I have two arrays

我有两个数组

array1 (
    "akey1" => "dfksjhf"
    "akey2" => "adasjkgffs"
    "akey3" => "afkjhsafshfkah"
)

array2 (
    "akey2" => "could be anything..."
)

I'm looking for a PHP function that I can supply the two arrays to and the following will happen:

我正在寻找一个PHP函数,我可以提供两个数组,并将发生以下情况:

If both arrays have an identical key (regardless of data) then remove the key from array 1 and return the remainder of array 1.

如果两个数组都具有相同的密钥(无论数据如何),则从数组1中删除密钥并返回数组1的其余部分。

The function if ran would return:

如果运行将返回的函数:

array3 (
    "akey1" => "dfksjhf"
    "akey3" => "afkjhsafshfkah"
)

Is there a PHP function that can do this already and if not what would be the fastest and most efficient way of doing this function in PHP?

是否有PHP函数可以执行此操作,如果不是,那么在PHP中执行此功能的最快和最有效的方法是什么?

Many Thanks

非常感谢

3 个解决方案

#1


11  

You are looking for array_diff_key():

您正在寻找array_diff_key():

$array3 = array_diff_key($array1, $array2);

#2


4  

array_diff_key should work for you:

array_diff_key应该适合你:

Returns an array containing all the entries from array1 whose keys are not present in any of the other arrays.

返回一个数组,其中包含array1中的所有条目,其中的键不存在于任何其他数组中。

$new_array = array_diff_key($array_1, $array_2);

#3


0  

Should be very simple with array_merge:

使用array_merge应该非常简单:

array_merge($array2, $array1);

array 2 first because from array 1 it need to be overwritten

数组2首先因为数组1需要被覆盖

or a simple like this;

或者像这样的简单;

function RemoveDuplicates($array1, $array2)
{
    foreach($array1 as $key=>$value)
    {
        if(array_key_exists($key, $array2)) {
            unset($array1[$key]);
        }
    }
    return $array1;
}

#1


11  

You are looking for array_diff_key():

您正在寻找array_diff_key():

$array3 = array_diff_key($array1, $array2);

#2


4  

array_diff_key should work for you:

array_diff_key应该适合你:

Returns an array containing all the entries from array1 whose keys are not present in any of the other arrays.

返回一个数组,其中包含array1中的所有条目,其中的键不存在于任何其他数组中。

$new_array = array_diff_key($array_1, $array_2);

#3


0  

Should be very simple with array_merge:

使用array_merge应该非常简单:

array_merge($array2, $array1);

array 2 first because from array 1 it need to be overwritten

数组2首先因为数组1需要被覆盖

or a simple like this;

或者像这样的简单;

function RemoveDuplicates($array1, $array2)
{
    foreach($array1 as $key=>$value)
    {
        if(array_key_exists($key, $array2)) {
            unset($array1[$key]);
        }
    }
    return $array1;
}