PHPUnit:断言两个数组相等,但元素的顺序不重要 [英] PHPUnit: assert two arrays are equal, but order of elements not important

查看:34
本文介绍了PHPUnit:断言两个数组相等,但元素的顺序不重要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当数组中元素的顺序不重要,甚至可能发生变化时,有什么好方法可以断言两个对象数组相等?

What is a good way to assert that two arrays of objects are equal, when the order of the elements in the array is unimportant, or even subject to change?

推荐答案

最简洁的方法是使用新的断言方法扩展 phpunit.但是现在这里有一个更简单的方法的想法.未经测试的代码,请验证:

The cleanest way to do this would be to extend phpunit with a new assertion method. But here's an idea for a simpler way for now. Untested code, please verify:

应用中的某处:

 /**
 * Determine if two associative arrays are similar
 *
 * Both arrays must have the same indexes with identical values
 * without respect to key ordering 
 * 
 * @param array $a
 * @param array $b
 * @return bool
 */
function arrays_are_similar($a, $b) {
  // if the indexes don't match, return immediately
  if (count(array_diff_assoc($a, $b))) {
    return false;
  }
  // we know that the indexes, but maybe not values, match.
  // compare the values between the two arrays
  foreach($a as $k => $v) {
    if ($v !== $b[$k]) {
      return false;
    }
  }
  // we have identical indexes, and no unequal values
  return true;
}

在您的测试中:

$this->assertTrue(arrays_are_similar($foo, $bar));

这篇关于PHPUnit:断言两个数组相等,但元素的顺序不重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆