PHP填充数组=>;stdClassObject,数据为空(年和月)


PHP Fill Array => stdClassObject with blank data (year and month)

PHP 5.4.21版

有一个数组(来自sql查询),如下所示:

Array(
...
 [4] => stdClass Object
    (
        [MakeModel] => Douglas DC-3
        [year] => 2011
        [month] => 4
        [zaehler] => 11
    )
[5] => stdClass Object
    (
        [MakeModel] => Douglas DC-3
        [year] => 2012
        [month] => 4
        [zaehler] => 2
    )
[6] => stdClass Object
    (
        [MakeModel] => Douglas DC-3
        [year] => 2013
        [month] => 3
        [zaehler] => 3
    )
...
)

对于javascript图表的使用,我需要将所有缺失的Years/Month填充为介于两者之间的"dummy object"。所以它应该是这样的:

Array(
[4] => stdClass Object
    (
        [MakeModel] => Douglas DC-3
        [year] => 2011
        [month] => 4
        [zaehler] => 11
    )
[5] => stdClass Object
    (
        [year] => 2011
        [month] => 5
    )
[6] => stdClass Object
    (
        [year] => 2011
        [month] => 6
    )
...
[7] => stdClass Object
    (
        [MakeModel] => Douglas DC-3
        [year] => 2012
        [month] => 4
        [zaehler] => 2
    )
... until today
)

这是我第二个与时间/日期相关的问题。使用php的日期/时间函数真的很难。谢谢你的帮助!

这听起来确实像是您可能会考虑在数据库中解决的问题。

举个例子,你有一个这样的表格,其中包含了你需要范围内的所有月份

month_id   year   month
1          2011   1
2          2011   2
...
*          20**   12

你修改了包含飞机信息的表格,比如这个

airplane_id   makemodel     zaehler  month_id
1             Douglas DC-3  11       4
...

然后,你可以进行左加入,以获得所有月份的飞机列表,这些列表匹配:

SELECT
  m.`year` AS `year`,
  m.`month` AS `month`,
  a.`makemodel` AS `makemodel`,
  a.`zaehler` AS `zaehler`
FROM `months` AS m
LEFT JOIN `airplanes` AS a
  ON m.`month_id` = a.`month_id`
ORDER BY `year` ASC, `month` ASC

结果集可能如下所示:

year  month  makemodel     zaehler
2011  1      NULL          NULL
2011  2      NULL          NULL
2011  3      NULL          NULL
2011  4      Douglas DC-3  11
...

具有与时间增量相关的固定ID的表的概念来自维度表的数据仓库概念。您将在大多数数据仓库概念中找到日期维度表(通常具有更精细的日期/时间行值)。

当然,这并不意味着这样的表只在数据仓库应用程序中有用。您在调度应用程序和其他需要"时隙"概念的情况下找到了这种表。