简体   繁体   中英

Compare values from two Arrays PHP

I have two Arrays with Objects in it. I want to compare each property of the array with each other.

function compare ($array1, $array2)
{
        $uniqueArray = array();
        for ($i = 0; $i < count($array1); $i++)
        {
            for ($j = 0; $j < count($array2); $j++)
            {
                if(levenshtein($array1[$i]->getCompany(), $array2[$j]-     >getCompany() > 0 || levenshtein($array1[$i]->getCompany(), $array2[$j]->getCompany()) < 3))
                {
                    //add values to $unqiueArray    
                }
            }
        }
        print_r($uniqueArray);
}

I'm not sure if my code is right. The iteration over the arrays and then the compare is that the right approach?

Object Properties:

private $_company;
private $_firstname;
private $_sirname;
private $_street;
private $_streetnumber;
private $_plz;
private $_place;

All prperties are strings.

You shouldn't use for (expr1; expr2; expr3) for iterating arrays; it's better to use foreach (array_expression as $value) Also, you are comparing every element on array1 with every element on array2, but if there's a match you compare them again later. Try something like this

foreach($array1 as $k1 => $v1) {
    foreach($array2 as $k2 => $v2) {
        if(your_condition()) {
            $uniqueArray[] = $v1;
            unset($array2[$k2])
        }
    }
}

Or maybe do some research on array_uintersect or array_walk

  • In the if , one parenthesis is mis-placed, which probably is the main problem and does unexpected results.
  • levenstein is not a trivial operation, you shouldn't do it two times just to compare it, it's better to store the result in a variable.
  • Without more details about the input and expected output, it's impossible to help you more.

Here is the code fixed.

function compare ($array1, $array2)
{
        $uniqueArray = array();
        for ($i = 0; $i < count($array1); $i++)
        {
            for ($j = 0; $j < count($array2); $j++)
            {
                $companyNamesLevenstein = levenshtein($array1[$i]->getCompany(), $array2[$j]->getCompany());
                if($companyNamesLevenstein > 0 || $companyNamesLevenstein < 3)
                {
                    $uniqueArray [] = $array1[$i];  
                }
            }
        }
        print_r($uniqueArray);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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