如何将默认数组添加到给定的数组列表?

时间:2019-01-03 09:13:32

标签: php

从查询中,获得名称年份和月份名称及其比率。从查询来看,一年只有4个月。那么,如何将默认比率为0.0的其他缺失月份添加到以下数组中?

$data = array();
foreach($result as $key => $val){
    $data[$val['name']][$val['year']][date('F', strtotime("2000-".$val['month']."-01"))]= $val['rate'];
}

1 个答案:

答案 0 :(得分:1)

$data = array();
foreach($result as $key => $val){
    if(!isset($data[$val['name']][$val['year']])) {
        //Initialize year array
        $data[$val['name']][$val['year']] = array(
        "January" => "0.0","February" => "0.0","March" => "0.0","April" => "0.0","May" => "0.0","June" => "0.0","July" => "0.0","August" => "0.0","September" => "0.0","October" => "0.0","November" => "0.0","December" => "0.0"
        ); 
    }
    $data[$val['name']][$val['year']][date('F', strtotime("2000-".$val['month']."-01"))]= $val['rate'];
}

初始化上面代码中给出的年数组