簡體   English   中英

PHP自定義CSV讀取,不同列和行的獨立回顯

[英]PHP custom CSV read, independent echos for different columns and rows

我有一個簡單的CSV,其中有6列。

編輯:在下面我找不到錯誤,這與選擇一個鍵並將其用作我認為的變量有關:

$handle = fopen('hire_pa_amps.csv',"r");
while($values = fgetcsv($handle))
{
foreach('$values[0]' as $value0)
{
    echo($value0);
}
foreach('$values[1]' as $valuepound)
{
    echo('&pound'.$valuepound);
}
echo ('<br>'); }
fclose($handle); 



The data from the CSV file looks like this:
 "H/H ELECTRONICS VX200, 100 watts/channel stereo amplifier",70,30,20
  Electrovoice CP1800,84,36,24

在此期間,我設法以某種方式進行了處理(暫時可以使用),但我仍然想知道上面代碼中的問題所在(如何在使用foreach的同時選擇數組中的鍵並獨立進行操作) )。 所以我現在做的解決方案是:

$handle = fopen('hire_pa_amps.csv','r') or die("can't open file");

echo('<table class="pricesTable">');
while($csv_line = fgetcsv($handle)) {
    list($column1, $column2, $column3, $column4) = $csv_line;

    echo('<tr>');

    echo    '<td>'.$column1.'</td>'.
            '<td>'.'&pound'.$column2.'</td>'.
            '<td>'.'&pound'.$column3.'</td>'.
            '<td>'.'&pound'.$column4.'</td>';
    echo('</tr>');
    }
fclose($handle) or die("can't close file");
echo('</table>');

如果您將CSV更改為包括列標題,然后在下面的代碼中編輯列選擇,則此方法將起作用:

function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
    return FALSE;

$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
    while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
    {
        if(!$header)
            $header = $row;
        else
            $data[] = array_combine($header, $row);
    }
    fclose($handle);
}
return $data;
}

$csvArray = csv_to_array('hire_pa_amps.csv');
echo "<table>
<tr>
    <th>Product Name</th>
    <th>Price</th>
    <th>Markup</th>
    <th>VAT</th>
</tr>
";
foreach($csvArray as $currentProduct){
    echo "  <tr>
    <td>" . $currentProduct['Product Name'] . "</td>
    <td>" . $currentProduct['Price'] . "</td>
    <td>" . $currentProduct['Markup'] . "</td>
    <td>" . $currentProduct['VAT'] . "</td>
</tr>
";
}
echo "</table>";

我認為您沒有考慮過使用foreach()將CSV正確解析為數組的方式,而是試圖在$ values上循環時嘗試在$ values [0]上循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM