1

For example I wanted to do something like

php sample.php [csv file] [column name]

it should display all data based on the specified column name. My code below just gets the first column but I wanted it to be a variable based on column name

CURRENT CODE

function getCSV($csv){
    $file = fopen($csv, 'r');
    while (!feof($file) ) {
        $lines[] = fgetcsv($file, 1024);
    }
    fclose($file);
    return $lines;
}

$csv = getCSV($argv[1]);
foreach ($csv as $values) {
    $row1[] = $values[0];
}
print_r($row1);

SAMPLE CSV

ID,Name
1,Amy
2,Ana 
3,Ava

EXPECTED OUTPUT

php sample.php sample.csv ID
1
2
3

php sample.php sample.csv Name
Amy
Ana
Ava

How do I do this?

3
  • take each csv row and explode Commented Aug 27, 2015 at 15:37
  • explode can be tricky if you're relying on consistent delimiters, and it'll fail on delimiters embedded in values. Commented Aug 27, 2015 at 15:38
  • Try to print_r($csv); after you set $csv from the getCSV() function. See what it looks like at that point, and that might help you loop over it. Commented Aug 27, 2015 at 15:40

1 Answer 1

1

thanks for all your help, eventually got it.

function getColumn($csv, $column){
    $header = array_shift($csv);
    $col = array_search($column, $header); 
    foreach ($csv as $row) {      
        $array[] = $row[$col]; 
    }
    return $array;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.