[英]Compare the data of two arrays using foreach PHP
I'm currently trying to compare the data of two arrays against eachother. 我目前正在尝试将两个数组的数据相互比较。 My code looks something like the one below: 我的代码如下所示:
foreach ($arrayOne as $one) {
$variable = $one['one'];
foreach ($arrayTwo as $two) {
if ($two == $variable) {
echo "Match!";
}
}
}
However, it only compares against the first element in $arrayTwo
, it's not looping through everything $arrayTwo
. 但是,它仅与$arrayTwo
中的第一个元素进行比较,没有遍历$arrayTwo
所有$arrayTwo
。 Why is this? 为什么是这样? Furthermore, is there a MORE EFFICIENT way to accomplish what I'm trying to do? 此外,还有其他更有效的方法来完成我要尝试的操作吗?
SNIPPET of Array One: 阵列一的SNIPPET:
array (
0 =>
array (
'paper_item_id' => 1,
'type' => 1,
'cost' => 20,
'is_member' => false,
'label' => 'Blue',
'prompt' => 'Blue',
'layer' => 1500,
),
1 =>
array (
'paper_item_id' => 2,
'type' => 1,
'cost' => 20,
'is_member' => false,
'label' => 'Green',
'prompt' => 'Green',
'layer' => 1500,
),
2 =>
array (
'paper_item_id' => 3,
'type' => 1,
'cost' => 20,
'is_member' => false,
'label' => 'Pink',
'prompt' => 'Pink',
'layer' => 1500,
),
3 =>
array (
'paper_item_id' => 4,
'type' => 1,
'cost' => 20,
'is_member' => false,
'label' => 'Black',
'prompt' => 'Black',
'layer' => 1500,
),
)
SNIPPET of Array Two: 阵列2的SNIPPET:
array (
0 => 'Blue',
1 => '
Purple Bat Wings',
2 => '
Black Motorbike',
3 => '
Test Scarf',
4 => '
Black',
5 => '
Green',
6 => '
Referee Jersey',
7 => '
Stethoscope',
8 => '
Custom Hoodie',
9 => '
',
)
The array_diff
(or array_diff_assoc
in your case) function returns the values that differs in two (or more) arrays. array_diff
(或您的情况下为array_diff_assoc
)函数返回两个(或多个)数组中不同的值。 If return value is empty, they don't differ at all. 如果返回值为空,则它们完全没有区别。
A more efficient way would be to make an associative array from the $arrayOne
values: 一种更有效的方法是从$arrayOne
值中创建一个关联数组:
$check = array();
foreach ($arrayOne as $one) {
$check[$one['one']] = true;
}
foreach ($arrayTwo as $two) {
if (isset($check[$two])) {
echo 'Match! <br/>';
}
}
The actual problem in the original code is that the explode()
code is returning an array where each element in $arrayTwo
begins with a newline, except the first one. 原始代码中的实际问题是explode()
代码返回一个数组,其中$arrayTwo
中的每个元素$arrayTwo
换行符开头,但第一个除外。 But the corresponding values in $arrayOne
don't have newlines, so they don't match. 但是$arrayOne
的相应值没有换行符,因此它们不匹配。 You need to fix the explode()
code, which isn't shown in the question. 您需要修复explode()
代码,该代码未在问题中显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.