构建一个多维数组php

时间:2014-03-27 11:12:18

标签: php arrays

我从awstats文件生成这个数组$months,如下所示:

Array
(
    [0] => Array
        (
            [0] => 10
            [1] => 37
            [2] => 11
        )

    [1] => Array
        (
            [0] => 11
            [1] => 34
            [2] => 19
        )

    [2] => Array
        (
            [0] => 12
            [1] => 20
            [2] => 11
        )

)

哪个$months[0][0]代表一个月的数量以及$months[0][1]个数据。我想要做的是使用它的数据构建一个具有一年中所有月份的数组,如果它没有一个数组到0。 像这样:

Array
(
    [0] => Array
        (
            [0] => 01
            [1] => 41
            [2] => 52
        )

    [1] => Array
        (
            [0] => 02
            [1] => 74
            [2] => 66
        )

    [2] => Array
        (
            [0] => 03
            [1] => 40
            [2] => 83
        )
    [3] => Array
        (
            [0] => 04
            [1] => 0
            [2] => 0
        )

    [4] => Array
        (
            [0] => 05
            [1] => 0
            [2] => 0
        )

    [5] => Array
        (
            [0] => 06
            [1] => 0
            [2] => 0
        )

依此类推......有什么办法可以实现这个目标吗?非常感谢!

1 个答案:

答案 0 :(得分:0)

这是我的想法(如果我理解你的问题):

首先,创建另一个包含12个元素的数组($ sortedMonths),然后用空数据填充它们:

$sortedMonths = array();
for ($i = 1; $i <= 12; $i++) {
    $sortedMonths[] = array($i, 0, 0);
}

/*
    Array
    (
        [0] => Array
            (
                [0] => 1,
                [1] => 0,
                [2] => 0
            )
        ...
        [11] => Array
            (
                [0] => 12,
                [1] => 0,
                [2] => 0
            )
    )
*/

然后循环$ months并将数据分配给$ sortedMonths的相应元素:

foreach ($months as $month) {
    $sortedMonths[$month[0]-1] = $month;
}