比较数组不打印差异 [英] Comparing arrays not printing the differences

查看:87
本文介绍了比较数组不打印差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的测试代码:

$a = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"21");

$b = array("Peter"=>"35", "Ben"=>"21", "Joe"=>"43");

function leo_array_diff($a, $b) {
    $map = array();
    foreach($a as $val) $map[$val] = 1;
    foreach($b as $val) unset($map[$val]);
    return array_keys($map);
}

print_r(leo_array_diff($a, $b));

echo "<br>";

print_r(array_diff($a, $b));

这是它的打印输出:

Array ( [0] => 37 ) 
Array ( [Ben] => 37 )


我将指的是leo_array_diff()函数:


i'm going to be referring to the leo_array_diff() function:

第一个问题:

如您所见,peter是相同的数字,所以很好. $a ben和$b ben不同. $a$b joe不同.但这只是表明本是不同的.

as you can see, peter is the same number so thats good. $a ben and $b ben is different. $a and $b joe is different. but it is only showing ben is different.

也许是因为$a joe 21与$b ben是21吗?我该如何改变呢?彼得需要与彼得对应,本需要与本对应,等等...

maybe because $a joe 21 is same as $b ben is 21? how can i change that? peter needs to correspond with peter, ben needs to correspond with ben, etc...

第二个问题:

本是不同的,是的,因为37和21在print_r中只显示Array ( [0] => 37 ).如何显示Array ( [0] => 21 )?调用函数时如何编辑函数而不交换参数?

Ben is different, yes, because 37 and 21 but in the print_r, it only shows Array ( [0] => 37 ). how can i make it show Array ( [0] => 21 )? How do I edit the function and not swapping the parameter when calling the function?

推荐答案

首先,您对

返回一个数组,其中包含来自array1的所有其他数组中不存在的所有条目.

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

它不返回索引Joe,因为值21在第一个数组中.

It's not returning the index Joe because the value 21 is in the first array.

现在,为什么您的功能不起作用?好吧,让我们一步一步来.

Now, why is your function not working? Well let's go step by step.

这是您的第一个foreach后您的地图的样子:

Here's what your map is looking like after your first foreach:

array(
    '35' => '1',
    '37' => '1',
    '21' => '1'
)

然后,在第二遍foreach中,您将遍历数组并删除值匹配的键.因此,基本上,您将删除索引35和索引21,这就是为什么仅保留索引37的原因. 这里的真正问题是因为您没有在任何地方检查名字.

Then, in your second foreach, you're looping through the array and removing the key where the value matches. So basically, you're removing the index 35 and index 21 which is why only the index 37 remains. The real problem here is because you're not checking for the name anywhere.

这是您的功能的替代方法:

Here's an alternative to your function:

function leo_array_diff($a, $b) {

    $map = array();

    foreach($a as $name => $value){

        // The name is not found in the second array
        // Or the value is different from the first array
        if(!isset($b[$name]) || $b[$name] != $value)
            $map[$value] = 1;

    }

    return array_keys($map);

}

var_dump为:

array(2) {
    [0]=>
        int(37)
    [1]=>
        int(21)
}

这篇关于比较数组不打印差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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