本文介绍了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:断言两个数组相等,但是元素的顺序并不重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 12:16