【问题标题】:PHP - trying to create an aray with a for loop but the order isn't rightPHP - 尝试使用 for 循环创建数组,但顺序不正确
【发布时间】:2018-03-09 07:48:26
【问题描述】:

我正在尝试创建一个包含 7 个项目的数组。一周中的每一天。但是进来的数据可能会丢失几天。如果数据丢失,我希望该数组当天“没有数据”。

问题是当我尝试生成数组时,它没有按我的预期排序。

$recordArray =

Array
(
    [0] => Array
        (
            [calories] => 368
            [date] => 2018-03-04
        )

    [1] => Array
        (
            [calories] => 126
            [date] => 2018-03-06
        )

    [2] => Array
        (
            [calories] => 86
            [date] => 2018-03-07
        )

    [3] => Array
        (
            [calories] => 83
            [date] => 2018-03-08
        )

)

PHP 代码:

$xArray = array();
for ($i = 0; $i <= 6; $i++) {
    if (array_key_exists($i, $recordArray)) {
        $xArray[] = $recordArray[$i]["date"];
    } else {
        $xArray[] = "no data";
    }
}
print_r($xArray); 

我得到的结果:

Array
(
    [0] => 2018-03-04
    [1] => 2018-03-06
    [2] => 2018-03-07
    [3] => 2018-03-08
    [4] => no data
    [5] => no data
    [6] => no data
)

我期待的结果:

Array
(
    [0] => 2018-03-04
    [1] => no data
    [2] => 2018-03-06
    [3] => 2018-03-07
    [4] => 2018-03-08
    [5] => no data
    [6] => no data
)

【问题讨论】:

  • 你为什么期待第二个例子?给定示例输入,第一个正是您编写的代码。
  • 因此,您的数组中存在键 0,1,2,3。显然你需要几天的其他检查。

标签: php arrays for-loop


【解决方案1】:

这是正确的逻辑:

// init array with "no data" value
$xArray = array_fill(0, 7, 'no data');

// iterate over your records
foreach ($recordArray as $record) {
    // From your date - get the number of week in a day
    $weekDay = date('w', strtotime($record['date']));
    // Modify the key in $xArray
    $xArray[$weekDay] = $record['date'];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多