,'descr'=>,'unit'=>,";f">
当前位置:Gxlcms > PHP教程 > 求教php如何创建一个带键名的空数组,后期再赋值

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

时间:2021-07-01 10:21:17 帮助过:14人阅读

刚接触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);

[] 格式是PHP 5.4 及以上版本才有的数组简写格式

$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] =>
)

)

人气教程排行