开发者

how do i get data of particular line in csv file from php?

开发者 https://www.devze.com 2023-04-11 18:27 出处:网络
fegtcsv does the work for fetching data of csv file in php I wrote this code to fetch data from my input file

fegtcsv does the work for fetching data of csv file in php I wrote this code to fetch data from my input file

<?php
$file_handle = fopen("input.csv", "r");
while(!feof($file_handle)){
    $line_of_text=fgetcsv($file_handle,3020);
    $a= $line_of_text[1];
 开发者_StackOverflow社区   $b=$line_of_text[2];
    $c=$line_of_text[3];
    $d=$line_of_text[4];
   }
   fclose($file_handle);
?>

now what actually i want is to do is some matematical operation between third data ( which is $c ) in each line. for eg. add the $c in line 1 with $c of line 2. and some more mathematical operation. I will be able to do this only if I can get those data as c1, which would be $c of first line c2 which would be $c of second line. But I din't find how to do that. the above script prints every line of the file. I have no control over which data of which line ( or row ) to print. how do I do that ? any thing I am missing to read or learn ? please let me know.


Every time you call fgetcsv you get another line. Therefore:

while (!feof($file_handle)){
    $line_of_text = fgetcsv($file_handle, 3020);
    $a1 = $line_of_text[1];
    $b1 = $line_of_text[2];
    $c1 = $line_of_text[3];
    $d1 = $line_of_text[4];

    $line_of_text = fgetcsv($file_handle, 3020);
    $a2 = $line_of_text[1];
    $b2 = $line_of_text[2];
    $c2 = $line_of_text[3];
    $d2 = $line_of_text[4];

    $line_of_text = fgetcsv($file_handle, 3020);
    $a3 = $line_of_text[1];
    $b3 = $line_of_text[2];
    $c3 = $line_of_text[3];
    $d3 = $line_of_text[4];

    echo $a1 + $a2 + $a3;
}

Tip: you can also use loops within loops...


Well try this lines, after you store each line in an array...

$csv = array();
$file = fopen('source.csv', 'r');
while (($result = fgetcsv($file,0,";")) !== false)
{
$csv[] = $result;
}
fclose($file);



function content_to_columns($data){
foreach ($data as $line=>$value){
$data[$line]=explode(";",$value);
}
print_r[$data]; //comment when not needed.
}

content_to_columns($csv_file); //

then you can really get any value knowing the line and the columns number lets say your data is

A | B
10| 0
20|20

$csv[0][0] is 10

Doing operational math with it is like:

$csv[0][0]*=5;  //multiplies by 5 the cell value
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号