简体   繁体   中英

Comparing & Counting Matched Values of Two Associative Arrays - PHP

I have been researching comparing two associative arrays, which I have only been able to do with a fair degree of accuracy. I have read all similar threads on SO but none have solved or addressed the issue I am having, which is, while comparing two associative arrays the test data will successfully show the appropriate matches, however when I attempt to count the number of matched values, I am getting some strange results.

EDIT:

<?php
$data    = array(
    'Alpha' => array(
        'peace' => 0,
        'art' => 1,
        'trend' => 0,
        'night' => 1,
        'shop' => 0
    ),
    'Beta' => array(
        'peace' => 1,
        'art' => 1,
        'trend' => 1,
        'night' => 1,
        'shop' => 0
    ),
    'Gamma' => array(
        'peace' => 0,
        'art' => 1,
        'trend' => 1,
        'night' => 1,
        'shop' => 0
    )
);
$choices = array(
    'peace' => 0,
    'art' => 1,
    'trend' => 0,
    'night' => 1,
    'shop' => 0
);
function compare($data, $choices)
{
    foreach ($data as $city => $name)
    {
        echo $city . '<br>';
        foreach ($name as $key => $value)
        {
            ($choices[$key] === $value) ? $match = 'match' : $match = 'no';
            ($choices[$key] === $value) ? $i++ : $i = 0;
            echo $key . ':' . $value . ':' . $choices[$key] . ':' . $match . '<br>';
        }
        echo 'Matches:' . $i . '<br><br>';
    }
}
compare($data, $choices);
?>

OUTPUT DATA

Format of data is as follows
-----------------------------
name of key:$data value:$choices value:is match

Alpha
peace:0:0:match
art:1:1:match
trend:0:0:match
night:1:1:match
shop:0:0:match
Matches:5

Beta
peace:1:0:no
art:1:1:match
trend:1:0:no
night:1:1:match
shop:0:0:match
Matches:2

Gamma
peace:0:0:match
art:1:1:match
trend:1:0:no
night:1:1:match
shop:0:0:match
Matches:2

'Alpha' should return 5 matches, which it does. 'Beta' should return 3, it returns 2. 'Gamma' should return 4, it returns 2.

Any help would be greatly appreciated. Thank you in advance.

The problem is how you are incrementing the count with a ternary statement. When you do

($choices[$key] === $value) ? $i++ : $i = 0;

It will reset $i to zero any time it encounters a non-match.

Using a simple conditional instead should give you the correct count.

if ($choices[$key] === $value) $i++;

You can initialize $i to 0 before the inner foreach loop.

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