当前位置: 代码迷 >> PHP >> 求教php怎么创建一个带键名的空数组,后期再赋值
  详细解决方案

求教php怎么创建一个带键名的空数组,后期再赋值

热度:59   发布时间:2016-04-28 19:04:04.0
求教php如何创建一个带键名的空数组,后期再赋值
刚接触php,不知道能否先创建一个带键名的空数组,后期使用时在赋值。因为此数组的键名个数是变化的,不能直接定义数组。
我的想法如下:

...
$strkeys= "'tagname'=>,'descr'=>,'unit'=>,";
for($w= 1; $w<= $days; $w++)
{
    $strkeys= $strkeys."'".$w."日'=>,";
}
$strkeys= $strkeys."'Total'=>";
$excelres[]= array($strkeys);
//print_r($excelres);

但使用print_r($excelres);后得到结果和想的不一样,如下:
Array ( [0] => Array ( [0] => 'tagname'=>,'descr'=>,'unit'=>,'1日'=>,'2日'=>,'3日'=>,'4日'=>,'5日'=>,'6日'=>,'7日'=>,'8日'=>,'9日'=>,'10日'=>,'11日'=>,'12日'=>,'13日'=>,'14日'=>,'15日'=>,'16日'=>,'17日'=>,'18日'=>,'19日'=>,'20日'=>,'21日'=>,'22日'=>,'23日'=>,'24日'=>,'25日'=>,'26日'=>,'27日'=>,'28日'=>,'29日'=>,'30日'=>,'Total'=> ) [1] => Array ( [0] => 'tagname'=>,'descr'=>,'unit'=>,'1日'=>,'2日'=>,'3日'=>,'4日'=>,'5日'=>,'6日'=>,'7日'=>,'8日'=>,'9日'=>,'10日'=>,'11日'=>,'12日'=>,'13日'=>,'14日'=>,'15日'=>,'16日'=>,'17日'=>,'18日'=>,'19日'=>,'20日'=>,'21日'=>,'22日'=>,'23日'=>,'24日'=>,'25日'=>,'26日'=>,'27日'=>,'28日'=>,'29日'=>,'30日'=>,'Total'=> ) ) 

------解决方案--------------------
首先你创建数组的格式就不对.

$strkeys= ['tagname'=>'',
           'descr'=>'','unit'=>''
];
$days=30;
for($w= 1; $w<= $days; $w++)
{
    $strkeys[$w.'日']='';
}
$strkeys['Total']='';
print_r($strkeys);

------解决方案--------------------

$strkeys= array('tagname'=>'','descr'=>'','unit'=>'');
$days = 31;
for($w= 1; $w<= $days; $w++)
{
$strkeys[$w.'日'] = '';
}
$strkeys['Total'] = '';
$excelres[]= $strkeys;

print_r($excelres);



Array
(
    [0] => Array
        (
            [tagname] => 
            [descr] => 
            [unit] => 
            [1日] => 
            [2日] => 
            [3日] => 
            [4日] => 
            [5日] => 
            [6日] => 
            [7日] => 
            [8日] => 
            [9日] => 
            [10日] => 
            [11日] => 
            [12日] => 
            [13日] => 
            [14日] => 
            [15日] => 
            [16日] => 
            [17日] => 
            [18日] => 
            [19日] => 
            [20日] => 
            [21日] => 
            [22日] => 
            [23日] => 
            [24日] => 
            [25日] => 
            [26日] => 
            [27日] => 
            [28日] => 
            [29日] => 
            [30日] => 
            [31日] => 
            [Total] => 
        )

)
  相关解决方案