使用php中的foreach循环向2d数组添加键值

时间:2017-05-03 01:31:39

标签: php arrays

foreach($objPHPExcel->getWorksheetIterator() as $worksheet)
        {
            echo '<table border ="1px" width ="50%" float:left overflow:auto>' . "\n";
            foreach ($objWorksheet->getRowIterator() as $row) {
                echo '<tr>' . "\n";
                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false);
                $y =0;
                foreach ($cellIterator as $cell) {
                    $promptData[$x][$y] = $cell->getValue();
                    $cellIndex = $cell->getCoordinate();
                    $promptData[$x][$y]['Index'] = $cellIndex;
                    echo '<td>' . $promptData[$x][$y] . '</td>' .'<td>' . $cell->getCalculatedValue() . '</td>' . "\n";
                    $y++;
                }
                $x++;
                echo '</tr>' . "\n";
            }
            echo '</table>' . "\n";
        }

我想在我正在使用的2d数组中存储单元格的索引 $ promptData [$ x] [$ y] ['Index'] = $ cellIndex; 但是任何人都无法帮助它。

1 个答案:

答案 0 :(得分:0)

问题是您首先将值$prompt[$x][$y]定义为值,然后将其定义为数组:

$promptData[$x][$y] = $cell->getValue();
$cellIndex = $cell->getCoordinate();
$promptData[$x][$y]['Index'] = $cellIndex;
echo '<td>' . $promptData[$x][$y] . '</td>' .'<td>' . $cell->getCalculatedValue() . '</td>' . "\n";

尝试将值分配给单元格的数组元素,然后只回显该数组元素而不是整个数组:

$promptData[$x][$y] = [
    'Value' => $cell->getValue(),
    'Index' => $cell->getCoordinate()
];
echo '<td>' . $promptData[$x][$y]['Value'] . '</td>' .'<td>' . $cell->getCalculatedValue() . '</td>' . "\n";