如何通过PHP从CSV文件中提取特定数据?

时间:2016-02-12 13:25:08

标签: php csv

因此,我目前创建了一个可以上传和查看CSV表单的页面。我在上传方面和阅读文档等方面做得很好但是如何从文档中间选择一个确切的信息?例如,我想知道我的第二个活动名称的总浮动。我该怎么做?这是我目前的代码。

<?php
$file = file('Uploads/uploadfile.csv');
$i = 0;
foreach($file as $line){
if($i > 1) {
list($activityid,$activitystatus,$wbscode,$wbsname,$activityname,$keymilestones,$originalduration,$remainingduration,$plannedstart,$plannedfinish,$totalfloat,$variancebl1startdate,)=explode(",", $line);  

echo "<h1>$activityname</h1>";
echo "<b>Activity ID: </b>$activityid<hr>";
echo "<b>WBS Code: </b>$wbscode<hr>";
echo "<b>WBS Name: </b>$wbsname<hr>";
echo "<b>Activity Status: </b>$activitystatus<hr>";
echo "<b>Key Milestones: </b>$keymilestones<hr>";
echo "<b>Original Duration: </b>$originalduration<hr>";
echo "<b>Remaining Duration: </b>$remainingsuration<hr>";
echo "<b>Planned Start: </b>$plannedstart<hr>";
echo "<b>Planned Finish: </b>$plannedfinish<hr>";
echo "<b>Total Float: </b>$totalfloat<hr>";
echo "<b>Variance B11 Start Date: </b>$variancebl1startdate<hr>";
}
$i++;
}
?>

感谢。

1 个答案:

答案 0 :(得分:0)

&#39;爆炸(&#34;,&#34;,$ line);&#39;返回一个数组。 您必须获得一个数组,其中索引是来自csv的列中的名称。 您可以新访问此数组,以便提取或查阅具有索引名称的任何特定数据。

实施例:    我是一个带有FirstName,LastName和Email的.csv文件给我的客户。

/**
 * Store csv data to array
 * 
 */
$file_path    = "customers.csv";
$file_content = file( $file_path );


/**
 * Store customers data with associative indexes
 * 
 */
$arr_data = array();
foreach ($file_content as $row) {
    $arr_data[] = explode(',', trim($row));
}

$arr_customers = array();
$first_row     = NULL;
foreach ($arr_data as $row) {

    //store content for first array -> FirstName, LastName, Email
    if (! $first_row) {
        $first_row = $row;

    } else {
        $arr_customers[] = array_combine($first_row, $row);
    }
}


/**
 * Retrieve data
 *
 */

//print email for all customers
foreach ($arr_customers as $customer) {
    echo $customer['Email'] . '<br>';
}

//print name for second customer
echo $arr_customers[1]['LastName'] . ', ' . $arr_customers[1]['FirstName'] . '<br>';