PHP或PHPUnit或Laravel是否具有用于递归数组比较的功能? [英] Does PHP or PHPUnit or Laravel have a function for recursive array comparison?

查看:83
本文介绍了PHP或PHPUnit或Laravel是否具有用于递归数组比较的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一些PHPUnit测试将Facebook称为"php-business-sdk",因此我可以确信Facebook的API会继续按预期运行.例如. FacebookAds\Object\Ad中的getInsights().

Some of my PHPUnit tests call the Facebook "php-business-sdk" so that I can be confident that Facebook's API is continuing to operate as I expect. E.g. getInsights() within FacebookAds\Object\Ad.

那些PHPUnit测试一直在使用assertEqualsCanonicalizing.

And those PHPUnit tests have been using assertEqualsCanonicalizing.

但是,测试仍然很脆弱; Facebook的API通常会更改 结果中的顶层数组的顺序(关联数组的数组),而且还会更改内部键的顺序关联数组.

However, the tests are still brittle; Facebook's API often changes not just the order of the top-level array in the result (an array of associative arrays) but also the order of the keys inside the associative arrays.

所以,我真正需要的是assertEqualsCanonicalizing的版本,该版本也是递归的,并且与该顶级数组中关联数组的键排序无关.

So what I really need is a version of assertEqualsCanonicalizing that is recursive and agnostic to the sorting of the keys of the associative arrays within that top-level array too.

如果这样的功能已经存在(我可能在PHP,PHPUnit,Laravel或其他地方),我宁愿自己也不编写代码.是吗?

I'd rather not code my own if such a function already exists (maybe in PHP, PHPUnit, Laravel, or elsewhere). Does it?

P.S.这是结果的简化示例:

P.S. Here is a simplified example of a result:

[
  {
    "Spend": "$3,009",
    "Campaign ID": 3335626793661,
    "Reach": 37640,
    "Unique Inline Link Clicks": 2368
  },
  {
    "Spend": "$1,030",
    "Campaign ID": 3335626793662,
    "Reach": 1620,
    "Unique Inline Link Clicks": 231
  }
]

(想象一下,下一次API返回相同的数据,但是在支出"之前写入了到达",并且对象的顺序也可以更改.)

(Imagine next time the API returns the same data but with "Reach" being written before "Spend", and the order of the objects can change too.)

P.S.这不是链接问题的重复,因为我是专门问如何不了解 inner 数组键的排序顺序.

P.S. This is not a duplicate of the linked question because I'm specifically asking how to be agnostic of the sorting order of the inner array keys.

推荐答案

没有in_array的本地方法可以递归工作.

There isn't a native method for in_array which works recursively.

但是许多人已经通过这样的助手解决了这个问题:

But many people have solved this issue with a helper like this one:

    private function in_array_recursive($needle, $haystack, $strict = true)
    {
        foreach ($haystack as $value) {
            if (($strict ? $value === $needle : $value == $needle) || (is_array($value) && $this->in_array_recursive($needle, $value, $strict))) {
                return true;
            }
        }
        return false;
    }

这篇关于PHP或PHPUnit或Laravel是否具有用于递归数组比较的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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