0

i have a csv file where the header line is in row 1 not row 0 how can i convert a csv in this situation. I have seen good versions of converting a csv file where the header row is at row[0] as

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;
}

please can someone assist me in the situation where row[1] is the header row.

3 Answers 3

1

You can do like this :

            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)
            {
                $i=0;
                while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
                {
                    if($i==0)
                    {
                      $i++;
                      continue;   //SKIP FIRST ROW
                    }
                    if(!$header)
                        $header = $row;
                    else
                        $data[] = array_combine($header, $row);
                }
                fclose($handle);
            }
            return $data;
            }
Sign up to request clarification or add additional context in comments.

Comments

1

Out of interest, if the headers are on row 1, what is on row 0? Is it blank?

In any case:

$i = 0;
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
    $i++;
    if ($i == 1) {
        continue; // Or do something else?
    } elseif ($i == 2) {
        $header = $row; // Get the headers on row 1
    } else {
        $data[] = $row; // Get the data on row 2 and above
    }
}

Alternatively:

while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
    $data[] = $row;
}

var_dump($data[1]); // This is the header

for ($i = 2, $j = count($data); $i < $j; $i++) {
    var_dump($data[ $i ]); // Each row of data
}

1 Comment

use $i++ before continue otherwise $i will always be equal to 0.
0

you can use fgetcsv and store results into an array like this

$file = fopen("path/to/csv","r");
$list=array();

//saving in list 
while ($row=fgetcsv($file)) {
  $list[]=$row;
}

then you can run a for loop starting $i = 2

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.