求教php如何建立一個帶鍵名的空數組,後期再賦值

來源:互聯網
上載者:User
剛接觸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] =>
)

)
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.