简体   繁体   English

在PHP中使用foreach循环将键值添加到二维数组

[英]add key value to 2d array using foreach loop in php

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";
        }

I want to store index of the cell in the 2d array I am using $promptData[$x][$y]['Index'] = $cellIndex; 我想将单元格的索引存储在2d数组中,我正在使用$ promptData [$ x] [$ y] ['Index'] = $ cellIndex; But it does not work can anyone help. 但任何人都无法帮助。

The problem is you're defining the value $prompt[$x][$y] first as a value, then as an array: 问题是您首先将值$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";

Try assigning the value to an array element for the cell, then echoing just that array element rather than the whole array: 尝试将值分配给单元格的数组元素,然后仅回显该数组元素而不是整个数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM