仅当在数组A中找不到数组时才返回数组的键 [英] Return keys of array only if not found in array A
问题描述
我有两个数组,一个是自定义的.
I have two arrays one is self defined.
$fields = array( "first_name" => "test", "last_name" => "Test", "phone" =>"111-111-1111, "id" => 1234");
另一个是从csv文件的第一行中获取的.它将返回一个像这样的数组
the other is grabbed from the first row of a csv file. which will return an array like so
$headers = array ("fname" => "test", "last_name" => "Test", "phone"=> "123-123-1234");
然后,如果$ headers数组中的键与$ fields数组中的任何键都不匹配,我想返回一个错误.如果$ fields数组中的键不是全部出现在$ headers数组中,也可以.
I then want to return an error if there is a key in $headers array doesn't match any of the keys in $fields array. Its okay if the keys in the $fields array aren't all present in the $headers array.
例如,上面的两个数组应该返回错误,因为键fname在$ fields数组中不存在,而不是因为id在$ headers数组中缺失.
For example the two arrays above should return an error because the key fname does not exist in the $fields array but not because the id is missing in the $headers array.
我尝试使用带有多个循环的if语句进行试验,但是我正在寻找一种更好的方法,我认为我可以操纵array_diff方法,但是没有运气.
I tried experimenting with if statements with multiple loops but I am looking for a better way I thought I could manipulate the array_diff method but have had no luck.
$dif_keys = array_diff($fields, $headers);
推荐答案
两件事:
-
如果要检查
$ headers
中是否所有键是否存在于$ fields
中,请使用array_diff_key
而不是array_diff
.array_diff
将仅比较值.
If you want to check if all keys from
$headers
are present in$fields
, usearray_diff_key
instead ofarray_diff
.array_diff
will only compare values.
更改参数的顺序.diff函数返回后一个参数中不存在的第一个参数的值,因此如果 $ fields
包含一些不在 $ headers中的键无关紧要
,您要先放置 $ headers
.
Change the order of the arguments. The diff functions return the values of the first argument that aren't present in the subsequent arguments, so if it doesn't matter that $fields
has some keys that aren't in $headers
, you want to put $headers
first.
所以我认为您需要的代码是:
So I think the code you need is:
$diff = array_diff_key($headers, $fields);
您可以将 $ diff
评估为布尔值.(例如 if($ diff){...
)如果为空,则将其评估为false,这意味着 $ headers
中的所有键在中均具有对应的键> $ fields
.
You can evaluate $diff
as a boolean. (e.g. if ($diff) {...
) If it is empty, it will evaluate as false, which means all keys in $headers
had corresponding keys in $fields
.
这篇关于仅当在数组A中找不到数组时才返回数组的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!