I am trying to compare two PHP arrays, that have different information in them, but both have the same key "id" which im trying to compare against.
我试图比较两个PHP数组,它们中有不同的信息,但两者都有相同的密钥“id”我试图比较。
First array:
第一个数组:
Array
(
[0] => Array
(
[id] => 59
[number] => 0002319411QT17D
[type] => 2
[rate] => 1
[site] => 776
[reading] => 0.00
[activity] => 1
[distance] => 0.000
)
[1] => Array
(
[id] => 60
[number] => 0000149450TR36E
[type] => 1
[rate] => 1
[site] => 777
[reading] => 0.00
[activity] => 1
[distance] => 0.000
)
[2] => Array
(
[id] => 61
[number] => 0000112211TR135
[type] => 1
[rate] => 2
[site] => 777
[reading] => 0.00
[activity] => 1
[distance] => 0.000
)
)
I then have this second array:
然后我有第二个数组:
Array
(
[0] => Array
(
[id] => 59
[emp_inv] => 1
[emp_gen] => 1970-01-01 12:00:00
)
[2] => Array
(
[id] => 59
[emp_inv] => 2
[emp_gen] => 1970-01-01 12:00:00
)
[3] => Array
(
[id] => 59
[emp_inv] => 3
[emp_gen] => 1970-01-01 12:00:00
)
)
I simply want to know of the [id] in the first array appears in the second array.
我只是想知道第一个数组中的[id]出现在第二个数组中。
e.g. [id] => 59 appears in both arrays, but id 60 does not.
例如[id] => 59出现在两个数组中,但id 60没有出现。
I've tried various PHP functions such as array_assoc to get the differences but it just returns blank arrays, not sure if this has something to so with it being an array inside of another array.
我已经尝试了各种PHP函数,例如array_assoc来获取差异,但它只返回空白数组,不确定是否有这样的东西,因为它是另一个数组中的数组。
Hope someone can help, and thanks :)
希望有人能帮忙,谢谢:)
1 个解决方案
#1
1
You can find the IDs that exist in both arrays using array_column()
(if you're on PHP 5.5 or above):
您可以使用array_column()找到两个数组中存在的ID(如果您使用的是PHP 5.5或更高版本):
$commonIds = array_intersect(array_column($first, 'id'), array_column($second, 'id'));
Example. If you're on an earlier version of PHP, here's an alternative implementation (recommended from the PHP manual) - or construct something manual using a few loops.
例。如果你使用的是早期版本的PHP,这里有一个替代实现(从PHP手册中推荐) - 或者使用一些循环构建一些手册。
If you then want to check if an ID exists in both arrays, just do $exists = (in_array(123, $commonIds)); // false
如果您想检查两个数组中是否存在ID,只需执行$ exists =(in_array(123,$ commonIds)); //假
#1
1
You can find the IDs that exist in both arrays using array_column()
(if you're on PHP 5.5 or above):
您可以使用array_column()找到两个数组中存在的ID(如果您使用的是PHP 5.5或更高版本):
$commonIds = array_intersect(array_column($first, 'id'), array_column($second, 'id'));
Example. If you're on an earlier version of PHP, here's an alternative implementation (recommended from the PHP manual) - or construct something manual using a few loops.
例。如果你使用的是早期版本的PHP,这里有一个替代实现(从PHP手册中推荐) - 或者使用一些循环构建一些手册。
If you then want to check if an ID exists in both arrays, just do $exists = (in_array(123, $commonIds)); // false
如果您想检查两个数组中是否存在ID,只需执行$ exists =(in_array(123,$ commonIds)); //假