如何在php中对数组内的值进行分组?

时间:2011-12-13 20:18:33

标签: php arrays multidimensional-array sorting

我有这种情况$result

[result] => Array
    (
        [Jeffrey] => Array
            (
                [date] => Array
                    (
                        [0] => 1294439732
                        [1] => 1294074456
                        [2] => 1295041663
                    )
                [amt] => Array
                    (
                        [0] => 6.90
                        [1] => 19.50
                        [2] => 19.50
                    )
            )
        [John] => Array
            (
                [date] => Array
                    (
                        [0] => 1294439732
                        [1] => 1294074456
                        [2] => 1295041663
                    )
                [amt] => Array
                    (
                        [0] => 6.90
                        [1] => 19.50
                        [2] => 19.50
                    )
            )
)

我想要完成的是:

[result] => Array
    (
        [Jeffrey] => Array
            (
                [date] => Array
                    (
                        [0] => 1294439732
                           [amt] => Array(
                             [0] => 6.90
                         )
                        [1] => 1294074456
                           [amt] => Array(
                             [0] => 19.50
                         )
                        [2] => 1295041663
                           [amt] => Array(
                             [0] => 19.50
                         )
                    )
            )
        [John] => Array
            (
                [date] => Array
                    (
                        [0] => 1294439732
                           [amt] => Array(
                             [0] => 6.90
                         )
                        [1] => 1294074456
                           [amt] => Array(
                             [0] => 19.50
                         )
                        [2] => 1295041663
                           [amt] => Array(
                             [0] => 19.50
                         )
                    )
            )
)

我可能有错误的数组格式,但我们的想法是每个date都有一个共同作用amt,而我希望这个数字在日期内

不确定如何继续重新组织此数组看起来像那样。 $结果[ '日期'] 我想我需要做一个foreach循环并将$result['date'] and $result['amt']放在一起。

任何人都有任何想法?

感谢

1 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西

$newArray = array();
foreach ($results as $user => $data) {
    $newArray[$user] = array();
    $newArray[$user]['date'] = array();
    for ($x = 0; $x < sizeof($results[$user]['date']); $x++) {
        $newArray[$user]['date'][$x] = array();
        array_push($newArray[$user]['date'][$x], $results[$user]['date'][$x]);
        array_push($newArray[$user]['date'][$x], array('amt' => array($results[$user]['amt'][$x])));
    }
}

var_dump($newArray);

不确定为什么你想要所有这些数组,尤其是amt中的数组,因为只有1个元素。