且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Php:如何计算两个“相似"数组之间的差异对象?

更新时间:2023-11-29 19:59:16

我已经制作了似乎比较ok"的函数:我连接"两个数组的属性以制作字符串",然后使用 strcmp() 函数返回结果.因此,当值不同时,它们会更改为字符串,而当涉及到子"数组时,它们会转换为 string = "Array" 所以比较 == 0 所以 "sub" 数组被忽略(这正是我想要的).

I've made the function that seems to compare "ok": I "concatenate" the properties of both arrays to make "strings" then use the strcmp() function to return the result. So, when the values are different they're changed to string, and when it comes to "sub" arrays, they're converted to string = "Array" so the comparison == 0 so the "sub" arrays are ignored (which is precisely what I wanted).

它有效.如果你发现一个例子可以告诉我它不起作用,请在评论中与我分享.谢谢!

It works. If you find an example that could show me that it doesn't work, please share it with me in a comment. Thanks!

$difference = array_udiff($tab_json, $tab, function($a, $b) {
    $d=array_diff_assoc(get_object_vars($a), get_object_vars($b));
    if (count($d)>0) {
        $s0='';
        $s1='';
        foreach ($d as $k=>$val) {
            $r0=(string)$val;
            $r1=(string)$b->$k;
            $l0 = mb_strlen($r0);
            $l1 = mb_strlen($r1);
            for (;$l0<$l1;$l0++) {
                $r0=' '.$r0;
            }   
            for (;$l1<$l0;$l1++) {
                $r1=' '.$r1;
            }   
            $s0.=$r0;
            $s1.=$r1;
        }   
        return strcmp($s0,$s1);
    }   
    return 0;
});
echo "difference = "; var_export($difference); echo "\n";