1

Assume my csv file will get a two dimensional array, how to put them in $array[][]?

if (($handle = fopen($_SERVER['DOCUMENT_ROOT']."/file.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        for ($c=0; $c < $num; $c++) {
            $dtary[$d][$c] = $data[$c];
            if ($c == $num) {
                 $d++;
            }
        } 
    }
    fclose($handle);
}
var_dump($dtary);

I am getting only last row of csv file.

0

1 Answer 1

1

There is no way that $d is ever incremented based on your for() loop conditions. The code inside the loop simply isn't run when $c==$num.

This is a method that actually works and offers the benefits of not calling count() nor incrementing counters.

Code: (Demo)

if(($handle=fopen($_SERVER['DOCUMENT_ROOT']."/file.csv","r"))!==FALSE){
    while(($data=fgetcsv($handle,1000,","))!==FALSE){
        $inner=[];             // start a fresh inner array
        foreach($data as $d){
            $inner[]=$d;       // build inner array with current row's data
        }
        $dtary[]=$inner;       // push row data as a subarray into result array
    }
    fclose($handle);
}
var_export($dtary);

While I would urge your to implement my code snippet, if you wanted to try to salvage your original code, you could do something like this:

if(($handle=fopen($_SERVER['DOCUMENT_ROOT']."/file.csv","r"))!==FALSE){
    $d=0;
    while(($data=fgetcsv($handle,1000,","))!==FALSE){
        $num=count($data);
        for($c=0; $c<$num; $c++){
            $dtary[$d][$c]=$data[$c];
        }
        $d++;
    }
    fclose($handle);
}
var_dump($dtary);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the codes sir. Why the code inside for loop isn't incrementing? I don't understand that part.
You had an "illogical" condition inside the loop. This part $c < $num; of the for loop tells the loop when to break. If you had something like $c <= $num; then the final iteration would allow $c==$num to be true. That is just an example, you shouldn't change the for condition because it would cause other problems. Does that make sense to you? or should I try to explain differently?

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.