我有一个CSV文件,下面的代码用于将CSV的内容放入多维数组中。
<?php
$val = $_GET['articleid'];
//URL Pass STring
$arrCSV = array();
// Open the CSV
if (($handle = fopen("../articles/artlist.csv", "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row
$c = count($data);
//Populate the array
for ($x=0;$x<$c;$x++) {
$arrCSV[$key][$x] = $data[$x];
}
$key++;
} // end while
// Close the CSV file
fclose($handle);
} // end if
?>
我的第一部分是输出整个数组。
我认为以下代码是错误的:(
<?php
for ( $row = 1; $row <$arrCSV; $row++ )
{
echo ''.$arrCSV[$row]['6'].'';
}
?>
然后我只想输出其中一列[*] [6]。
在我尝试其余的事情之前,我想我应该先到这里。
任何指导都会有所帮助。
我正在努力学习,到目前为止,我已经走到了这一步。
谢谢
答案 0 :(得分:1)
这不起作用吗?:
<?php
$val = $_GET['articleid'];
//URL Pass STring
$arrCSV = array();
// Open the CSV
if (($handle = fopen("../articles/artlist.csv", "r")) !==FALSE) {
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
$arrCSV[] = $data;
} // end while
// Close the CSV file
fclose($handle);
} // end if
?>
答案 1 :(得分:1)
我使用此功能将CSV转换为数组
function csv2array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n")
{
$array = array();
$size = strlen($string);
$columnIndex = 0;
$rowIndex = 0;
$fieldValue = "";
$isEnclosured = False;
for($i=0; $i<$size;$i++)
{
$char = $string{$i};
$addChar = "";
if($isEnclosured)
{
if($char == $enclosureChar)
{
if($i+1<$size && $string{$i+1} == $enclosureChar)
{
$addChar = $char;
$i++;
}
else
{
$isEnclosured = false;
}
}
else
{
$addChar=$char;
}
}
else
{
if($char==$enclosureChar)
{
$isEnclosured = true;
}
else
{
if($char==$separatorChar)
{
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue = "";
$columnIndex++;
}
elseif($char==$newlineChar)
{
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex=0;
$rowIndex++;
}
else
{
$addChar=$char;
}
}
}
if($addChar != "")
{
$fieldValue.=$addChar;
}
}
if($fieldValue)
{
$array[$rowIndex][$columnIndex] = $fieldValue;
}
return $array;
}
您可以像这样使用它:
<?php
$handle = fopen("../articles/artlist.csv", "r");
$arr = csv2array($handle);
print_r($arr);
?>
答案 2 :(得分:0)
这是解决方案
要访问CSV:
<?php
$val = $_GET['articleid'];
//URL Pass STring
$arrCSV = array();
// Open the CSV
if (($handle = fopen("../articles/artlist.csv", "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row
$c = count($data);
//Populate the array
for ($x=0;$x<$c;$x++) {
$arrCSV[$key][$x] = $data[$x];
}
$key++;
} // end while
// Close the CSV file
fclose($handle);
} // end if
?>
要在CSV中显示整个列:
<?php
for ( $row = 1; $row <$arrCSV; $row++ )
{
echo ''.$arrCSV[$row]['6'].'';
}
?>