比较两个平面关联数组之间的键值对[重复]

问题描述 投票:0回答:1

我有这两个

associative arrays

针阵列

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

干草堆阵列

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

我想检查

$a
是否与
b
及其确切的
key
value

匹配

并且如果

$a
中的每个键和值在
$b
中都完全匹配......我想将变量
$c
的值增加 1 等等...

正如我们从上面看到的,有 3 种可能的匹配...... 据称结果是将

$c
的值增加 3

$c = "3";

php arrays compare associative-array array-difference
1个回答
20
投票

编辑2

OP 实际上将

array_intersect_assoc()
用于其特定用例。(检查评论

原来的答案对他们的案例来说并没有多大用处!


您可以查看 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;
?>

键盘链接。

© www.soinside.com 2019 - 2024. All rights reserved.