相同的数组值不相等?

时间:2012-05-01 02:18:46

标签: php arrays matching

<?php
$bigArray = array(
    array('John','2012-03-29',1),
    array('Doe','2012-03-30',1),
    array('John','2012-03-31',2),
    array('Doe','2012-03-31',5),
    array('Tom','2012-03-31',5),
    array('John','2012-04-02',5),
    array('John','2012-04-02',21),
    array('John','2012-03-07',21)
);

$cache = array();
foreach ($bigArray as $v) {
    if (isset($cache[$v[1]])) {
        if ($cache[$v[1][1]] == $v[2]) {
            echo "Equal";
            $cache[$v[1]] = array($v[0].','.$cache[$v[1]][0], $v[2]);//append user to same value
        }
        else if ($cache[$v[1][1]] < $v[2]) {
            echo "Replacing value! ".$cache[$v[1]][0]. " to " .$v[0]."<br/>";
            $cache[$v[1]] = array($v[0], $v[2]);
        }
    } else {
        $cache[$v[1]] = array($v[0], $v[2]);
    }
}

print_r($cache);
?>

此脚本查找特定日期的最高值,并将其保存到新数组$cache

但是,当检查同一日期的最高值是否相等时,它会返回false?

array(
    array('Doe','2012-03-31',5),
    array('Tom','2012-03-31',5),
)

数组中的上述内容令我感到困惑。不应该算作一场比赛吗?

输出:

Replacing value! John to Doe
Replacing value! Doe to Tom
Replacing value! John to John
Array
(
    [2012-03-29] => Array
    (
        [0] => John
        [1] => 1
    )
    [2012-03-30] => Array
        (
        [0] => Doe
        [1] => 1
    )
    [2012-03-31] => Array
    (
        [0] => Tom
        [1] => 5
    )
    [2012-04-02] => Array
    (
        [0] => John
        [1] => 21
    )
    [2012-03-07] => Array
    (
        [0] => John
        [1] => 21
    )
)

2 个答案:

答案 0 :(得分:3)

没有太多细节,$v[1][1]似乎对我来说是非常荒谬的。它指的是原始数组中日期字符串的第二个字符。你可能意味着:

$cache[$v[1]][1]

答案 1 :(得分:2)

我猜这里,但可能代替:

$cache[$v[1][1]]

你应该写:

$cache[$v[1]][1]

大括号略有差异:)