PHP在多维数组中添加类似数据

时间:2011-06-29 06:35:13

标签: php arrays multidimensional-array

我有一个带有一些数据的多维数组。

    Array  ID      Date     Quantity
    66998  [0] [2011-05-11] [50]
           [1] [2011-05-15] [50]
           [2] [2011-05-15] [50]
    81158  [0] [2011-05-11] [25]
           [1] [2011-05-12] [60]
           [2] [2011-05-16] [60]
           [3] [2011-05-18] [60]

我想在同一周内将订单中的所有数量加起来。我可以用以下方式计算周数:

            $WeekNumber = date("W", $UnixTimestamp);

所以最终的数组应如下所示:

               Week Quantity
    66998  [0] [19] [150]
    81158  [0] [19] [85]
           [1] [20] [120]    

该数组是从MS SQL数据库生成的。

2 个答案:

答案 0 :(得分:1)

您可以使用array_reduce($array, 'function_name')一次一步地生成结果数组。

function calc_weeks($result, $row)
{
    . . .
    $WeekNumber = date("W", $UnixTimestamp);
    $result[$weekNumber] += $row['quantity'];
    return $result;
}
array_reduce($array, 'calc_weeks', array());

或者,您可以使用SQL来计算周数并以此方式汇总订单。在MySQL中,该函数称为WEEK()。对于MS SQL,有一个related question here

答案 1 :(得分:1)

操作我的3D array理论:(参见我在OP问题中的评论)

We have to go deeper...

<?php

    $array = array(66998 => array(array('ID' => 0,
                            'Date' => '2011-05-11',
                            'Quantity' => 50),
                            array('ID' => 1,
                            'Date' => '2011-05-15',
                            'Quantity' => 50),
                            array('ID' => 2,
                            'Date' => '2011-05-15',
                            'Quantity' => 50)
                            ),
                    81158   => array(array('ID' => 0,
                            'Date' => '2011-05-11',
                            'Quantity' => 25),
                            array('ID' => 1,
                            'Date' => '2011-05-12',
                            'Quantity' => 60),
                            array('ID' => 2,
                            'Date' => '2011-05-16',
                            'Quantity' => 60),
                            array('ID' => 3,
                            'Date' => '2011-05-18',
                            'Quantity' => 60)
                            ));

    $newArray = array();

    foreach($array as $subKey => $subArray) {

        foreach($subArray as $idArray) {

            $week = date("W", strtotime($idArray['Date']));

            $newArray["{$subKey}"]["{$week}"] = $idArray['Quantity'] + $newArray["{$subKey}"]["{$week}"];
        }
    }

    var_dump($newArray);

?>

产生您想要的结果(2D为简单起见):

array(2) {
  [66998]=>
  array(1) {
    [19]=>
    int(150)
  }
  [81158]=>
  array(2) {
    [19]=>
    int(85)
    [20]=>
    int(120)
  }
}

快乐的编码!