比较两个数组的值如何具有相同的键和长度

时间:2016-01-24 21:30:01

标签: php arrays

我想比较具有相同键(活动)且长度相同的两个数组的值。

阵列

$request->setLocale('nl_BE');

我希望有类似的东西:

$anna_array = array("soccer" => "10", "basketball" => "20", "atletics" => "40");
$john_array = array("soccer" => "15", "basketball" => "15", "atletics" => "45");

然后我会在结果中使用$ points:

<?php
if ($anna_array['soccer'] > $john_array['soccer']){
    $points = "1";
} else {
    $points = "0";
}
?>

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

只需使用foreach并通过键进行比较:

foreach($anna as $key => $val){
    if(array_key_exists($key, $john)){
         if($val > $john[$key]){
             $points["john"] += 1;
         } else {
             $points["anna"] += 1;
         }
    }
}

我希望我能正确理解你的问题。

答案 1 :(得分:2)

首先,您可以首先应用array_intersect_key然后array_keys来检索公用密钥。

$common_sports = array_keys(array_intersect_key($anna_array, $john_array));

然后,您可以使用array_fill_keys使用上面找到的相同键填充数组

$points_anna_array = $points_john_array = array_fill_keys($common_sports, 0);

这里生成的数组是:

 array(3) {
  ["soccer"]=>
  int(0)
  ["basketball"]=>
  int(0)
  ["atletics"]=>
  int(0)
}

现在你可以比较安娜和约翰的活动

foreach ($common_sports as $common_sport) {
    if ($anna_array[$common_sport] > $john_array[$common_sport]) {
        $points_anna_array[$common_sport]++;
    } else if ($anna_array[$common_sport] < $john_array[$common_sport]) {
        $points_john_array[$common_sport]++;
    }
}

此时$points_anna_array的值为:

array(3) {
  ["soccer"]=>
  int(0)
  ["basketball"]=>
  int(1)
  ["atletics"]=>
  int(0)
}

$points_john_array值:

array(3) {
  ["soccer"]=>
  int(1)
  ["basketball"]=>
  int(0)
  ["atletics"]=>
  int(1)
}

所以:

foreach ($common_sports as $common_sport) {
    echo sprintf(
       'Anna(%s) %d vs John(%s) %d'."\n",
       $common_sport, $points_anna_array[$common_sport],
       $common_sport, $points_john_array[$common_sport]
    );
}

这将输出:

Anna(soccer) 0 vs John(soccer) 1
Anna(basketball) 1 vs John(basketball) 0
Anna(atletics) 0 vs John(atletics) 1

Demo

要获得总分,您可以使用array_sum

echo "John's total score: ", array_sum($points_john_array);
echo "Anna's total score: ", array_sum($points_anna_array);