简体   繁体   中英

comparing values in 2 arrays in php - array_intersect doesn't work

I have the following arrays named investmentprogramscriteria and companyInvestmentProfil:

Array
(
[0] => Array
    (
        [criteriaID] => 55
        [criteriaIsMatchedIf] => 11, 12, 13
    )

[1] => Array
    (
        [criteriaID] => 54
        [criteriaIsMatchedIf] => 1
    )

[2] => Array
    (
        [criteriaID] => 52
        [criteriaIsMatchedIf] => 1
    )

)


Array
(
[0] => Array
    (
        [criteriaID] => 52
        [investmentprofileCriteriaAnswer] => 1
    )

[1] => Array
    (
        [criteriaID] => 54
        [investmentprofileCriteriaAnswer] => 1
    )

[2] => Array
    (
        [criteriaID] => 58
        [investmentprofileCriteriaAnswer] => 0
    )

[3] => Array
    (
        [criteriaID] => 59
        [investmentprofileCriteriaAnswer] => 1
    )

[4] => Array
    (
        [criteriaID] => 55
        [investmentprofileCriteriaAnswer] => 1
    )

)

I am trying to find out if the value of the criteriaID from the first array (investmentprogramscriteria ) exists in the second array (companyInvestmentProfil) AND IF the value of the key criteriaIsMatchedIf from the first array is equal to the value of the key investmentprofileCriteriaAnswer from the second array.

My current php code returns wrong result at this time:

if (array_intersect($investmentprogramscriteria,$companyInvestmentProfil))     {
    echo "Match";
 } else {
    echo "Not match";
 }

array_column() can extract the column indicated as a single dimension and indexes it by the next column indicated. Do this for both arrays and then use array_intersect_assoc() to check key and value:

if(array_intersect_assoc(
array_column($investmentprogramscriteria, 'criteriaIsMatchedIf', 'criteriaID'),
array_column($companyInvestmentProfil, 'investmentprofileCriteriaAnswer', 'criteriaID'))) {
    echo "Match";
} else {
    echo "No Match";
}

PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column() .

You can try the code with array_map:

$elements1 = array();
foreach($investmentprogramscriteria as $item) {
    $elements1[] = $item['criteriaID'] . $item['criteriaIsMatchedIf'];
}
$elements2 = array();
foreach($companyInvestmentProfil as $item) {
    $elements2[] = $item['criteriaID'] . $item['criteriaIsMatchedIf'];
}

if (array_intersect($elements1, $elements2))     {
    echo "Match";
} else {
    echo "Not match";
}

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