PHP组数组由2个不同的值组成

时间:2010-11-07 20:55:38

标签: php arrays multidimensional-array group-by

我有一个这样的数组:

Array
(
    [0] => Array
        (
            [datetime] => 2010-11-06 21:25:53
            [movieID] => 1197624
            [personID] => 0
            [more indexes]...
        )
    [1] => Array
        (
            [datetime] => 2010-11-06 21:32:56
            [movieID] => 1197624
            [personID] => 0
            [more indexes]...
        )
    [2] => Array
        (
            [datetime] => 2010-11-06 21:38:07
            [movieID] => 0
            [personID] => 0987657
            [more indexes]...
        )
    [3] => Array
        (
            [datetime] => 2010-11-06 21:55:09
            [movieID] => 0
            [personID] => 0987657
            [more indexes]...
        )
    [4] => Array
        (
            [datetime] => 2010-11-06 21:59:33
            [movieID] => 5467023
            [personID] => 0
            [more indexes]...
        )
)

在每个内部数组中,当[movieID]的数字不同于0时,[personID]将等于0,反之亦然。我想通过[movieID]将数组分组(如果它不同于0)和[personID]如果它不同于0

所以结果将是这样的:

Array
(
    [1197624] => Array
        (
            [0] => Array
                (
                    [datetime] => 2010-11-06 21:32:56
                    [movieID] => 1197624
                    [personID] => 0
                    [more indexes]...
                )
            [1] => Array
                (
                    [datetime] => 2010-11-06 21:25:53
                    [movieID] => 1197624
                    [personID] => 0
                    [more indexes]...
                )
        )
    [0987657] => Array
        (
            [0] => Array
                (
                    [datetime] => 2010-11-06 21:38:07
                    [movieID] => 0
                    [personID] => 0987657
                    [more indexes]...
                )
            [1] => Array
                (
                    [datetime] => 2010-11-06 21:55:09
                    [movieID] => 0
                    [personID] => 0987657
                    [more indexes]...
                )
        )
    [5467023] => Array
        (
            [0] => Array
                (
                    [datetime] => 2010-11-06 21:59:33
                    [movieID] => 5467023
                    [personID] => 0
                    [more indexes]...
                )
        )
)

我通过这样的分组看到的唯一问题是[movieID]和[personID]有可能是相同的数字(当然在不同的索引中),但机会很少。

所以有人可以帮我分组这个数组???

1 个答案:

答案 0 :(得分:3)

基本上是这样的吗?

$replacement = array();
foreach($original as $item) {
    if ($item['movieID'] != 0)
        $replacement[ $item['movieID'] ][] = $item;
    else
        $replacement[ $item['personID'] ][] = $item;
}