在PHP中解析CSV文件 - 函数返回未定义的变量

时间:2013-11-19 15:32:44

标签: php arrays function fgetcsv

我正在尝试从csv文件中检索某些元素以插入到我们的客户端报告数据库中。我正在尝试编写一个解析数据并返回必要信息的函数。但是,我的函数返回一个未定义的变量,我不太清楚如何解决这个问题。我确定这是一个初学者的问题,但我仍然是在php中编写自己的函数和数组的新手。我很感激帮助!也没有API可以直接拨打以获得更可靠的数据源。

以下代码:

// Reading the csv file, returning an array of rows
$rows = array();

foreach (file('prerolldaily.csv') as $line){
    $rows[] = str_getcsv($line);
}   

function extractInfo($e){
    $returnImpressionsRow = $rows[$e][4];
    $returnClicksRow = $rows[$e][5];
    $returnCompletedViewsPercentage = $rows[$e][7];
    $returnCPM = $rows[$e][8];
    $returnTotalSpend = $rows[$e][9];
    $clientName = $rows[$e][11];
    $finalPercentage = substr($returnCompletedViewsPercentage, 0, -1);
    $finalCPM = substr($returnCPM, 1);
    $totalSpend = substr($returnTotalSpend, 1);
    return $clientName . " Impressions: ". $returnImpressionsRow . " Clicks: " . $returnClicksRow. " Completed Views: " . $finalPercentage . "%" . " CPM: $" . $finalCPM . " Total Spend: $" . $totalSpend;
}

// Tell browser to treat this as a Plain Text file
header('Content-Type: text/plain');

extractInfo(0);

print_r($rows)

屏幕输出:(我需要报告的客户数超过15个)删除了一些元素(客户名称)

Array
(
    [0] => Array
        (
            [0] => switch active/paused CLIENT NAME CLIENT NAME Sites Ads Pre-roll (30s)
            [1] => Day 12 out of 19 Nov 8, 2013 Nov 26, 2013
            [2] => $20.00
            [3] => $50.00
            [4] => 3,360
            [5] => 12
            [6] => 0.36%
            [7] => 57%
            [8] => $14.46
            [9] => $48.58
            [10] => edit placement copy placement delete see report attach ad
            [11] => CLIENT NAME
        )

1 个答案:

答案 0 :(得分:4)

您的函数中未定义

$rows,您需要将其作为参数发送:

function extractInfo($rows, $e){
    $returnImpressionsRow = $rows[$e][4];
    $returnClicksRow = $rows[$e][5];
    $returnCompletedViewsPercentage = $rows[$e][7];
    $returnCPM = $rows[$e][8];
    $returnTotalSpend = $rows[$e][9];
    $clientName = $rows[$e][11];
    $finalPercentage = substr($returnCompletedViewsPercentage, 0, -1);
    $finalCPM = substr($returnCPM, 1);
    $totalSpend = substr($returnTotalSpend, 1);
    return $clientName . " Impressions: ". $returnImpressionsRow . " Clicks: " . $returnClicksRow. " Completed Views: " . $finalPercentage . "%" . " CPM: $" . $finalCPM . " Total Spend: $" . $totalSpend;
}

...

extractInfo($rows, 0);

查看variable scope in the php manual