3

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

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 个结果:

  1. 第一个数组中时间比第二个数组更新的对象
  2. 第二个数组中时间比第一个数组更新的对象
  3. 第一个数组中的对象具有比第二个数组更新的“playertm”
  4. 第二个数组中具有比第一个数组更新的“playertm”的对象

有些结果可能不在每个数组中,需要返回,但是数组键总是匹配的。

我正在使用'array_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

谢谢你的帮助。

4

2 回答 2

1

我不确定为什么会发生这种情况,但使用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]
于 2014-01-20T14:58:03.183 回答
0

我希望,如果您可以在以下结构中重新构造数组,这将很容易,因此您可以从两个对象中进行 4 次组合。你可以根据需要对它们进行排序

[1] => stdClass Object
    (
        [matchID] => 1

        [tm] =>08:55:13
        [td] =>2014-01-16
        [playertm_date] => 2014-01-16
        [playertm_time] => 08:55:14

    )

另一种替代解决方案是 Json

于 2014-01-20T15:26:01.647 回答