我有一个数组,其中包含如下所示的对象,第一个数组:

Array
(
[1] => stdClass Object
    (
        [matchID] => 1
        [tm] => 2014-01-16 08:55:13
        [playertm] => 2014-01-16 08:55:14
    )

[2] => stdClass Object
    (
        [matchID] => 2
        [tm] => 2014-01-16 09:53:50
        [playertm] => 2014-01-16 09:53:52
    )

[3] => stdClass Object
    (
        [matchID] => 3
        [tm] => 2014-01-16 09:58:49
        [playertm] => 2014-01-16 09:58:57
    )

[4] => stdClass Object
    (
        [matchID] => 4
        [tm] => 2014-01-17 08:44:34
        [playertm] => 2014-01-17 08:44:35
    )
)

第二个数组:
Array
(
[3] => stdClass Object
    (
        [matchID] => 3
        [tm] => 2014-01-16 09:58:49
        [playertm] => 2014-01-16 09:58:57
    )

[4] => stdClass Object
    (
        [matchID] => 4
        [tm] => 2014-01-17 08:44:34
        [playertm] => 2014-01-17 08:44:38
    )

[5] => stdClass Object
    (
        [matchID] => 5
        [tm] => 2014-01-19 08:44:34
        [playertm] => 2014-01-19 08:44:38
    )
)

并尝试根据时间同步每个数组。我希望返回4个结果:
第一个数组中时间比第二个数组晚的对象
第二个数组中时间比第一个数组晚的对象
第一个数组中比第二个数组具有“playertm”的对象
第二个数组中比第一个数组具有“playertm”的对象
有些结果可能不在每个数组中,需要返回,但是数组键总是匹配的。
我使用的是“Alayay-Udiff'函数,到目前为止,有如下:
function tmCompare($a, $b)
{
    return strtotime($a->tm) - strtotime($b->tm);
}
function ptmCompare($a, $b)
{
    return strtotime($a->playertm) - strtotime($b->playertm);
}

$df1 = array_udiff($a, $b, 'tmCompare');
$df2 = array_udiff($b, $a, 'tmCompare');

$df3 = array_udiff($a, $b, 'ptmCompare');
$df4 = array_udiff($b, $a, 'ptmCompare');

它似乎返回差异,但是数组(4)在每2个函数中返回,而我只希望在时间大于而不是不同的情况下返回数组。
我试过了
return (strtotime($a->playertm) > strtotime($b->playertm)) ? -1 : 0;

相似,但似乎不能得到正确的结果。我是不是漏掉了一些简单的东西?
编辑:这里有一个快速的pastebin,可以让代码运行http://pastebin.com/gRz9v2kz
谢谢你的帮助。

最佳答案

我不知道为什么会这样,但是使用array_udiff()似乎违反直觉。我在两个函数中重写了需求,以执行比较并迭代数组:

function getCompareFunction($field)
{
        return function($a, $b) use ($field) {
                return strcmp($a->{$field}, $b->{$field});
        };
}

function getBigger($a, $b, $compare)
{
        $res = array();

        foreach ($a as $k => $v) {
                if (!isset($b[$k]) || $compare($v, $b[$k]) > 0) {
                        $res[$k] = $v;
                }
        }

        return $res;
}

$biggerTime = getCompareFunction('tm');
$biggerPlayerTime = getCompareFunction('playertm');

print_r(getBigger($a, $b, $biggerTime)); // [1, 2]
print_r(getBigger($b, $a, $biggerTime)); // [4, 5]
print_r(getBigger($a, $b, $biggerPlayerTime)); // [1, 2]
print_r(getBigger($b, $a, $biggerPlayerTime)); // [4, 5]

关于php - PHP多数组差异,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21220372/

10-09 08:21
查看更多