views:

54

answers:

1

I am using Codeigniter to parse an uploaded csv file (which is a multi-dimensional array) into a database. I have tried everything to parse the comma values correctly, but the "id" column in mysql comes up short, as it reads "text", and not "text,text,text". Help!?

    *For reference:*

    print_r($data['csvData']);

    Array ( [0] => Array ( [category,id] => text1,"text,text,text" )
            [1] => Array ( [category,id] => text2,"text,text,text" )
    )

    foreach($data['csvData'] as $row) {
                    foreach ($row as $item) {
                            $item=explode(",", $item); 
                            $results_array = array(
                                    'category' => $item[0],
                                    'id' => $item[1]
                                    );
                            $this->db->set($results_array);
                            $this->db->insert('table', $results_array);
                    }
    }
A: 

My uneducated guess:

$item=explode(",", $item); is exploding $item which is text1,"text,text,text", right? So it sees 4 commas, and explodes them. Therefore $item[0] will be "text1, $item[1] will be "text" $item[2] will be "text" and $item[3] will be "text".

You can try to set your delimiter in the csv as something other than a comma, and explode that.

Or you can concatenate the other items before inserting them into the db:

$item = explode(",", $item); 
$id_insert = $item[1].$item[2].$item[3];
//if you need to retain the commas in the id: 
//$id_insert = $item[1].','.$item[2].','.$item[3];
$results_array = array(
    'category' => $item[0],
    'id' => $id_insert,
);
$this->db->set($results_array);
$this->db->insert('table', $results_array);
stormdrain