【问题标题】:php compare two associative arrays [duplicate]php比较两个关联数组
【发布时间】:2012-05-03 05:09:23
【问题描述】:

我有这两个associative arrays

// 针阵列

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

// 干草堆数组

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

我想检查$a 是否与b 匹配,它与keyvalue 完全相同

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

正如我们从上面看到的那样,有 3 种可能的匹配... 并且据说结果将$c 的值增加了 3

$c = "3";

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

【问题讨论】:

  • 在我的情况下,数组是多维的,我解决了比较每个的序列化返回的问题

标签: php compare associative-array


【解决方案1】:

你可以查看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链接。

【讨论】:

  • 这不是我正在寻找的答案,先生......我最想要的是......每次有完全匹配的结果时 $c 都会增加
  • 也许我可以使用 array_intersect_assoc() 代替....然后只计算匹配结果...
  • 先生,我已经找到答案了... $check_result = count(array_intersect_assoc($a, $b));
  • 但仍然感谢.. 因为你给了我使用 rray_intersect_assoc() 的想法......
  • array_diff_assoc() 在我的情况下很有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多