php比较两个关联数组

时间:2012-04-22 07:45:07

标签: php compare associative-array

我有这两个associative arrays

//针阵列

$a = array(
"who" => "you", 
"what" => "thing", 
"where" => "place",
"when" => "hour"
);

// haystack数组

$b = array(
"when" => "time", 
"where" => "place", 
"who" => "you",
"what" => "thing"
);

我想检查$a是否与b匹配,并且确切keyvalue

如果$a中的每个键和值都与$b中的完全匹配....我想将变量$c的值递增1,依此类推。

我们从上面看到有3种可能的匹配...... 并且据推测结果是将$c的值增加3

$c = "3";

我希望有些天才可以帮助我...

1 个答案:

答案 0 :(得分:13)

你可以查看php的array_diff_assoc()函数或array_intersect()函数。

修改

以下是计算匹配值的示例:

<?php
  $a = array(
    "who" => "you", 
    "what" => "thing", 
    "where" => "place",
    "when" => "hour"
  );
  // the haystack array
  $b = array(
    "when" => "time", 
    "where" => "place", 
    "who" => "you",
    "what" => "thing"
  );
  $c = count(array_intersect($a, $b));
  echo $c;
?>

CODEPAD链接。