1

My CSV file has this structure

title;firstName;lastName;email;
Sir;Bob;Public;bob.p@gmail.com;

The first row shows the column names. Content starts with the second row. Now I want this to put into an associative array like this

array([0] => 
            array(
                   'title' => 'Sir', 
                   'firstName' => 'Bob', 
                   'lastName' => 'Public', 
                   'email' => 'bob.q@gmail.com'
            ) 
)

What I tried:

    $entities = array();

    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {

        $num = count($data);

        for ($c = 0; $c < $num; $c++) {

              $line = array();
               //save first row
               if ($row == 1) {
                  foreach (explode(';', $data[$c]) as $field) {
                      //dont save empty fields
                      if ($field != "") {
                         $fields[] = $field;
                         $line[$field] = array();
                      }
                   }
               }
               //go through contents and save them
               foreach ($fields as $field) {
                   for ($i = 2; $i < count($fields); $i++) {
                       $cust = explode(";", $data[$c]);
                       $line[$field][] = $cust[$i];
                   }
               }
               $entities[] = $line;
               $row++;
            }
        }

        fclose($handle);
    }   

This gives no error but a strange array that seems to be messed up. Any ideas how I can get my desired structure?

DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601
  • 3
    You have a `;` separated file yet you are specifying `,` as the separator. – Salman A Jan 08 '13 at 12:55
  • possible duplicate of [CSV to Associative Array](http://stackoverflow.com/questions/4801895/csv-to-associative-array) – Manse Jan 08 '13 at 12:58

2 Answers2

4

This should work:

$entities = array();
$header = fgetcsv($handle, 0, ";"); // save the header
while (($values = fgetcsv($handle, 0, ";")) !== FALSE) {
    // array_combine
    // Creates an array by using one array for keys and another for its values
    $entities[] = array_combine($header, $values);    
}
Salman A
  • 262,204
  • 82
  • 430
  • 521
0
$entities = array();
//Assuming you are able to get proper array from CSV
$data = array('title;firstName;lastName;email;', 'Sir;Bob;Public;bob.p@gmail.com;');
$num = count($data);

for ($c = 0; $c < $num; $c++) {

$line = array();
//save first row

foreach (explode(';', $data[$c]) as $field) {
    //dont save empty fields
    if ($c == 0) {
        if ($field != "") {
            $fields[] = $field;
            //$line[$field] = array();
        }
    } else {
        if ($field != "") {
            $line[$field] = $field;
        }
    }

}
if (count($line) > 0)
    $entities[] = $line;
}
Rajat Garg
  • 355
  • 1
  • 2
  • 11