-1

I want to load a CSV file dynamically into php and store it in an array. I can't get the array name changed to the form I want it to be. The first array should be numbered as normal, the second should contain the header of the CSV file.

This is my current function to solve the problem:

static function parseCSV($path){

        $fp = file($path);
        $array = array();
        for ($i = 0; $i < count($fp); $i++) {
            $e = explode("," , $fp[$i+1]);
            foreach($e as $data){
                $array[$e[0]][] = $data;
            }
        }
        
        print_r($array);
    }

This is the Output:

Array
(
    [Louis] => Array
        (
            [0] => Louis 
            [1] => 000               
            [2] => 01.01.2001
            [3] => Canada
        )

    [Hannah] => Array
        (
            [0] => Hannah
            [1] => 001              
            [2] => 02.02.2002             
            [3] => Germany        


        )
)

The output I would like:

Array
(
    [1] => Array
        (
            [name] => Louis 
            [id] => 000               
            [birthday] => 01.01.2001
            [country] => Canada
        )

    [2] => Array
        (
            [name] => Hannah
            [id] => 001              
            [birthday] => 02.02.2002             
            [country] => Germany        


        )
)

1 Answers1

0

You can create a new row data array with the specific array index:

static function parseCSV($path){
        $headers = ['name', 'id', 'birthday', 'country'];
        $fp = file($path);
        $array = array();
        for ($i = 0; $i < count($fp); $i++) {
            $rows = explode("," , $fp[$i+1]);
            foreach($rows as $row) {
                $associativeArray = array();
                foreach($row as $index=>$value) {
                    $associativeArray[$headers[$index]] = $value;   
        
                }
                array_push($array, $associativeArray);
            }
        }
        
        print_r($array);
    }

subodhkalika
  • 1,964
  • 1
  • 9
  • 15