【问题标题】:How to exact match both keys and values in both arrays in php [duplicate]如何在php中精确匹配两个数组中的键和值[重复]
【发布时间】:2018-06-29 13:32:36
【问题描述】:

我有两个数组,我想精确匹配数组的键和值,其中一个数组是三维或更多 示例

$arr1 = ['status'=>true,'message'=>'data saved']; 
$arr2 = ['status'=>true,'message'=>'data saved'];

在这种情况下,数组返回 1 但它们不相等

$arr1 = array("messagess"=>"data added","status" => true);
$arr2 = array("status" => true,'message'=>'data has been added'); 
echo count(array_intersect_assoc($arr1,$arr2));

如果两者完全匹配,则预期应该为真,否则为假。试过array_intersect()等方法都失败了。

请指导!

提前致谢

【问题讨论】:

  • 显示您尝试过的代码。编写一些 foreach 循环来解决这个问题应该不难
  • 数组是三维或更多 -- 那么你可能有多维数组?该函数是否也应该检查内部数组是否相等?
  • 要检查数组是否相等只做 if ($arr1===$arr2) {/** 匹配 **/}

标签: php arrays


【解决方案1】:

您可以使用 array_intersect_assoc() 并计算结果数

  echo count(array_intersect_assoc($arr1,$arr2));

http://php.net/manual/en/function.array-intersect-assoc.php

如果计数中的数字与您要检查的索引键的数量相同,请检查两个数组是否相同,否则您将获得匹配的键值的数量

【讨论】:

  • but count of this $arr1 = array("messagess"=>"data added","status" => true); $arr2 = array("status" => true,'message'=>'数据已添加'); return 1 应该返回 0
  • 1 是正确的 .. 在您的示例中,您正在寻找 2 .. 所以一个键值匹配不是 2.. 答案更新了简要说明 .. 更多查看链接中的 php 手册跨度>
猜你喜欢
  • 1970-01-01
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 2021-01-26
  • 2017-02-11
  • 2012-11-13
  • 1970-01-01
相关资源
最近更新 更多