我有这个PHP数组:
array(
[1528840800] => 50 // 12 June 2018 22:00:00
[1531173600] => 37 // 9 July 2018 22:00:00
[1540940400] => 44 // 30 October 2018 23:00:00
[1543532400] => 9 // 29 November 2018 23:00:00
)
我如何获得完整的12个月数组,其中剩余月份值为零?
array(
[01] => 0
[02] => 0
[03] => 0
[04] => 0
[05] => 0
[1528840800] => 50 // 12 June 2018 22:00:00
[1531173600] => 37 // 9 July 2018 22:00:00
[08] => 0
[09] => 0
[1540940400] => 44 // 30 October 2018 23:00:00
[1543532400] => 9 // 29 November 2018 23:00:00
[12] => 0
)
此属性不适用于第二个值。
for ($i=1;$i<13;$i++) {
foreach ($array as $key => $value) {
if (date('m',$key)===sprintf('%02d', $i)) {
$fullmonths[date('d/m/Y',$key)] = $value;
break;
}else{
$fullmonths['XXXX/'.sprintf('%02d', $i).'/2018]=0;
}
}
}
非常感谢。
答案 0 :(得分:1)
只需进行一些更改即可正确跳至下个月。您可以在任何级别中断或继续循环。如果设置了continue 2
,则开始for循环的下一个触发。否则,您将填写默认值
for ($i=1;$i<13;$i++) {
foreach ($array as $key => $value) {
if (date('m',$key) === sprintf('%02d', $i)) {
$fullmonths[date('d/m/Y',$key)] = $value;
// If found skip to next month
continue 2;
}
}
$fullmonths['XX/'.sprintf('%02d', $i).'/2018'] = 0;
}
答案 1 :(得分:1)
了解您已经在做什么。
如果要重新使用原始数组,只需将$months
更改为$array
。
$array = [
"1528840800" => 50,
"1531173600" => 37,
"1540940400" => 44,
"1543532400" => 9
];
$months = [];
for ($i=1;$i <= 12;$i++) {
foreach($array as $time => $value) {
$date = date("n", $time);
if ($date == $i) {
$months[$time] = $value;break;
} else {
$months[$i] = 0;
}
}
}
var_dump($months);
如果您需要零填充数,只需将str_pad()
添加到[$i]
,如下所示:
[str_pad($i, 2, "0", STR_PAD_LEFT)]
答案 2 :(得分:0)
您可以使用STR_PAD_LEFT
尝试类似的操作并更新密钥。
$mainArray=array();
$output = array('1528840800' => '50', '1531173600' => '37', '1540940400' => '44', '1543532400' => '9');
for ($i=1; $i <= 12; $i++)
{
$value = str_pad($i, 2, "0", STR_PAD_LEFT);
$mainArray[$value] = 0; //set Everykey to Zero
}
foreach ($output as $key => $value)
{
$joy = gmdate("m", $key);
$mainArray[$key]=$value; //update the key
unset($mainArray[$joy]);
}