foreach循环中的数组值仅在最后一个值中打印

时间:2018-05-03 06:14:45

标签: php arrays foreach

我已经获得了月份中的foreach循环和数组打印中的总月份值计数数据,但只有最后一个值打印在数组中

foreach($rawData as $Data)
{
    $monthsss = $Data['month_no'];

    if($monthsss=='1')
    {
        $arrayF['jan'] = $Data['month_count'];
    }
    else
    {
        $arrayF['jan'] = '0';
    }

    if($monthsss=='2')
    {
        $arrayF['feb'] = $Data['month_count'];
    }
    else
    {
        $arrayF['feb'] = '0';
    }
 }

2 个答案:

答案 0 :(得分:0)

请修改您的代码,如下所示

foreach($rawData as $Data)
{
    $monthsss = $Data['month_no'];

    if($monthsss=='1')
    {
        $arrayF['jan'] = is_null($Data['month_count'])? 0 : $Data['month_count'];
    }


    if($monthsss=='2')
    {
        $arrayF['feb'] = is_null($Data['month_count'])? 0 : $Data['month_count'];
    }

 }

答案 1 :(得分:0)

当有人评论并询问请显示输入和预期输出。这不是为了给你更多的工作,但有很多方法可以实现你想要的但许多答案可能是错误的或需要更多代码(与接受的答案一样)。

假设这是您的数据:

$rawData = [
    ['month_no' => 1, 'month_count' => 1],
    ['month_no' => 2, 'month_count' => 1],
    ['month_no' => 3, 'month_count' => 1],
    ['month_no' => 4, 'month_count' => 1],
    ['month_no' => 1, 'month_count' => 2],
    ['month_no' => 6, 'month_count' => 2],
    ['month_no' => 7, 'month_count' => 6],
    ['month_no' => 12, 'month_count' => 4],
];

您只想要总结值吗?

<?php

$array = [];
foreach ($rawData as $data) {
    $m = strtolower(DateTime::createFromFormat('!m', $data['month_no'])->format('M'));
    $array[$m] = !isset($array[$m]) ? $data['month_count'] : $array[$m]+$data['month_count'];
}

print_r($array);

https://3v4l.org/vXgCL

Array
(
    [jan] => 3
    [feb] => 1
    [mar] => 1
    [apr] => 1
    [jun] => 2
    [jul] => 6
    [dec] => 4
)

或者您想要一个包含总和值的所有月份的数组:

<?php

$array = [];
foreach (range(1, 12) as $month) {
    $m = strtolower(DateTime::createFromFormat('!m', $month)->format('M'));

    $monthSet = array_filter($rawData, function ($v) use ($month) {
        return $v['month_no'] === $month;
    });

    $array[$m] = 0;
    foreach ($monthSet as $data) {
        $array[$m] += $data['month_count'];
    }
}

print_r($array);

https://3v4l.org/vqnnv

Array
(
    [jan] => 3
    [feb] => 1
    [mar] => 1
    [apr] => 1
    [may] => 0
    [jun] => 2
    [jul] => 6
    [aug] => 0
    [sep] => 0
    [oct] => 0
    [nov] => 0
    [dec] => 4
)

或者根据您的评论建议,或许甚至不关心月份的字符串。

<?php
$array = [];
foreach ($rawData as $data) {
    $m = $data['month_no'];
    $array[$m] = !isset($array[$m]) ? $data['month_count'] : $array[$m]+$data['month_count'];
}

print_r($array);

https://3v4l.org/7gKRo

Array
(
    [1] => 3
    [2] => 1
    [3] => 1
    [4] => 1
    [6] => 2
    [7] => 6
    [12] => 4
)

我们问的原因..