简体   繁体   English

如何比较 2 个不同长度的 arrays 到彼此

[英]How to compare 2 different length arrays to eachother

I'm trying to make a function that compares two different length arrays to each other and if they match then some actions are performed.我正在尝试制作一个 function 来比较两个不同长度的 arrays ,如果它们匹配,则执行一些操作。 Array1, cell1 compares to array2, cell1, cell2, cellN... Then Array1, cell2 compares to array2, cell1, cell2, cellN... Array1、cell1 与 array2、cell1、cell2、cellN 进行比较... 然后 Array1、cell2 与 array2、cell1、cell2、cellN 进行比较...

Something resembling this:类似这样的东西:

if(array1[$i]==array2[])
{
   // Some actions...
}

How can this be implemented?如何实施?

PHP has in_array for searching an array for a particular value. PHP 具有in_array用于在数组中搜索特定值。 So what about那么怎么样

foreach ($array1 as $search_item)
{
    if (in_array($search_item, $array2))
    {
        // Some actions...
        break;
    }
}

You can get the difference of the Arrays with the PHP function array_diff .您可以得到 Arrays 与 PHP function array_diff的区别。

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

Results in结果是

Array
(
    [1] => blue
)

You can use nested loops for this.您可以为此使用嵌套循环。

for($i=0; $i<count($array1); $i++){
    for($j=0; $j<count($array2); $j++){
        if($array1[$i] == $array2[$j]){
            //some action here
        }
    }
}

kindly correct the errors.请纠正错误。 im comparing the arrays values to display respectively with their paired one我将 arrays 值与它们配对的值进行比较以分别显示

if((cardnumb1[1]==123456789) && (passcode[1]==1234)) if((cardnumb1[1]==123456789) && (passcode[1]==1234))

                         else if ((cardnumb1[2]==987654321) && (passcode[2]==4567))

                         else if ((cardnumb1[3]==123789456) && (passcode[3]==7890))

Even if answered I think, just for reference, is good to know that you can make:即使回答我认为,仅供参考,很高兴知道您可以:

$array_1 = array(1,2,3,4,5);
$array_2 = array(2,4,6,8);

foreach (array_intersect($array_1,$array_2) as $match){
    //do something
}

NOTE: may give some problems with associative arrays.注意:可能会给关联的 arrays 带来一些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM