我一直在寻找我需要的地方,但我没有到达任何地方。不确定是不是因为我想要的东西是不允许的,或者我只是不知道如何正确地说出来找到解决方案。
我正在创建一个包含大量工作表的excel导出,因此有很多重复的代码,所以我做了一个foreach循环。问题是我在其中有变量的数组,我需要代码将这些特定的变量放到我需要它的位置。
$y1953 =& $workbook->add_worksheet('1953');
$y1958 =& $workbook->add_worksheet('1958');
$y1963 =& $workbook->add_worksheet('1963');
$y1978 =& $workbook->add_worksheet('1978');
$y1988 =& $workbook->add_worksheet('1988');
$y2003 =& $workbook->add_worksheet('2003');
$yearlist = array($y1953 => '1953', $y1958 => '1958', $y1963 => '1963', $y1978 => '1978', $y1988 => '1988', $y2003 => '2003');
foreach ($yearlist as $year => $yearnum){
$line = 1; # Start on line 2
# Write each line
foreach ($bll->rows AS $row) {
$numberlist = array (''=>'1', '2'=>'2', '3' => '3', '4' => '4');
foreach ($numberlist as $name => $num){
if ($row['gYear'.$name] === $yearnum){
$col = 0;
$year->write_string($line, $col, ''); $col += 1;
$year->write_string($line, $col, $row['name_last'.$name]);$col += 1;
$year->write_string($line, $col, $row['name_first'.$name]); $col += 1;
$year->write_string($line, $col, $row['name_last']); $col +=1;
if($row['session'. $num .'1'] === '1')
{
$year->write_number($line, $col, $row['session'. $num .'1'] );
}$col += 1;
if($row['session'. $num .'2'] === '1')
{
$year->write_number($line, $col, $row['session'. $num .'2'] );
}$col += 1;
if($row['session'. $num .'3'] === '1')
{
$year->write_number($line, $col, $row['session'. $num .'3'] );
}$col += 1;
if($row['session'. $num .'4'] === '1')
{
$year->write_number($line, $col, $row['session'. $num .'4'] );
}$col += 1;
if($row['session'. $num .'5'] === '1')
{
$year->write_number($line, $col,$row['session'. $num .'5'] );
}$col += 1;
if($row['session'. $num .'6'] === '1')
{
$year->write_number($line, $col, $row['session'. $num .'6'] );
}$col += 1;
$year->write_number($line, $col, '1'); $col +=1;
$year->write_string($line, $col, $row['notes']); $col += 1;
$line += 1;
}
}
}
$ yearlist是我遇到麻烦的数组。我需要第一个值“$ y1953”为$ year在foreach循环中的位置。现在,我的Excel工作表中没有显示任何内容。 那么有没有办法让代码只是将变量放在我需要它的位置?或者它可能是变量值?
我会以不同的方式做到这一点,但我正在制作这个excel导出的人想要一个特定的方式。
由于
答案 0 :(得分:1)
数组和对象不能用作键。这样做会导致警告:非法偏移类型。
http://php.net/manual/en/language.types.array.php
尝试在数组声明中切换键和值。
$yearlist = array('1953' => $y1953, '1958' => $y1958......etc.
比将你的foreach改为
foreach ($yearlist as $yearnum => $year)
答案 1 :(得分:0)
也许,你可以在循环中创建一个工作表。而不是:
$y1953 =& $workbook->add_worksheet('1953');
$y1958 =& $workbook->add_worksheet('1958');
$y1963 =& $workbook->add_worksheet('1963');
$y1978 =& $workbook->add_worksheet('1978');
$y1988 =& $workbook->add_worksheet('1988');
$y2003 =& $workbook->add_worksheet('2003');
$yearlist = array($y1953 => '1953', $y1958 => '1958',
$y1963 => '1963', $y1978 => '1978', $y1988 => '1988',
$y2003 => '2003');
试试这个:
$yearlist = array('1953', '1958', '1963', '1978', '1988', '2003');
foreach($yearlist as $value)
{
$sheet =& $workbook->add_worksheet($value);
//do the job with the year and new worksheet
}