импортировать данные из csv в mysql, используя cakephp

Я хочу импортировать данные из csv в таблицу mysql, используя cakephp.
Когда я запускаю функцию, она помещает нулевые значения в мою таблицу, и я считаю, что это формат моего массива $ data, вот мой код.

var $name = 'ScWidths'; var $scaffold; /* function import() { $messages = $this->ScWidth->import('scwidths.csv'); $this->set('messages', $messages); } 

* /

  function import() { // to avoid having to tweak the contents of // $data you should use your db field name as the heading name // eg: Post.id, Post.title, Post.description // set the filename to read CSV from $filename = TMP . 'uploads' . DS . 'Sc_widths' . DS . 'scwidths.csv'; // open the file $handle = fopen($filename, "r"); // read the 1st row as headings $header = fgetcsv($handle); // create a message container $return = array( 'messages' => array(), 'errors' => array(), ); // read each data row in the file $i = 0; while (($row = fgetcsv($handle)) !== FALSE) { $i++; $data = array(); // for each header field foreach ($header as $k=>$head) { // get the data field from Model.field if (strpos($head,'.')!==false) { $h = explode('.',$head); #die(debug($h)); $data[$h[0]][$h[1]]=isset($row[$k]) ? $row[$k] : ''; } // get the data field from field else { $data['ScWidth'][$head]=isset($row[$k]) ? $row[$k]: ''; } } $data['ScWidth']['section_id']=1; $this->ScWidth->create(); // success or not :/ if ($this->ScWidth->save($data)) { echo "success"; } } // close the file fclose($handle); // return the messages //return $return; } 

в моей отладочной точке он возвращает этот массив

 array( 'ScWidths' => array( 'chainage' => '0' ), 'Left_side' => '3.7' ), 'right_side' => '3.7' ), 'section_id' => (int) 1 ) ) 

журнал ошибок,

ничего…

Я считаю, что моя следующая ошибка в моем методе сохранения.

вот мой файл данных, просто задержитесь.

 ScWidths.chainage,ScWidths.Left_side,ScWidths.right_side 0,3.7,3.7 10,3.7,3.7 20,3.7,3.7 30,3.7,3.7 40,3.7,3.7 50,3.7,3.7 60,3.7,3.7 70,3.7,3.7 80,3.7,3.7 

исправил мой код, это работает на 100%, если кому-то нужен пример 🙂

Эта строка здесь верна

$data[$h[0]][$h[1]][$h[2]]=(isset($row[$k])) ? $row[$k] : '';

$h[2] никогда не будет определено.

Когда вы взорваетесь заголовочное имя, например «sc_widths.chainage» (с разделителем «.»), Вы получите

  • $h[0] = 'sc_widths';
  • $h[1] = 'chainage';

Вы никогда не получите $ h [2] с этими данными.

Поэтому исправление для вашей конкретной проблемы состоит в том, чтобы сбросить $ h [2] следующим образом:

$data[$h[0]][$h[1]]=(isset($row[$k])) ? $row[$k] : '';

 Here is working code. function import($filename) { $i = null; $error = null; $filename = $_SERVER['DOCUMENT_ROOT'] . '/dashboards/app/webroot/files/' .$filename; $handle = fopen($filename, "r"); $header = fgetcsv($handle); $return = array( //'messages' => array(), 'errors' => array(), ); while (($row = fgetcsv($handle)) !== FALSE) { $i++; $data = array(); foreach ($header as $k=>$head) { if (strpos($head,'.')!==false) { $h = explode('.',$head); $data[$h[0]][$h[1]]=(isset($row[$k])) ? $row[$k] : ''; } else { $data['Project'][$head]=(isset($row[$k])) ? $row[$k] : ''; } } $id = isset($row[0]) ? $row[0] : 0; if (!empty($id)) { $projects = $this->find('all', array('conditions' => array('Project.item_sku' =>$id))); if (!empty($projects)){ $apiConfig = (isset($projects[0]['Project']) && is_array($projects[0]['Project'])) ? ($projects[0]['Project']) : array(); //debug($apiConfig); //debug($data['Project']); $data['Project'] = array_merge($apiConfig,$data['Project']); }else { $this->id = $id; } } else { $this->create(); } //debug($data); $this->set($data); if (!$this->validates()) { //$this->_flash('warning'); //$errors = $this->ModelName->invalidFields(); if(!empty($this->validationErrors['item_name'])){ $limit = $this->validationErrors['item_name'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else if(!empty($this->validationErrors['brand_name'])){ $limit = $this->validationErrors['brand_name'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else if(!empty($this->validationErrors['manufacturer'])){ $limit = $this->validationErrors['manufacturer'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else if(!empty($this->validationErrors['feed_product_type'])){ $limit = $this->validationErrors['feed_product_type'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else if(!empty($this->validationErrors['product_description'])){ $limit = $this->validationErrors['product_description'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else if(!empty($this->validationErrors['bullet_point1'])){ $limit = $this->validationErrors['bullet_point1'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else if(!empty($this->validationErrors['bullet_point2'])){ $limit = $this->validationErrors['bullet_point2'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else if(!empty($this->validationErrors['bullet_point3'])){ $limit = $this->validationErrors['bullet_point3'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else if(!empty($this->validationErrors['bullet_point4'])){ $limit = $this->validationErrors['bullet_point4'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else if(!empty($this->validationErrors['bullet_point5'])){ $limit = $this->validationErrors['bullet_point5'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else if(!empty($this->validationErrors['quantity'])){ $limit = $this->validationErrors['quantity'] ; $return['errors'][] = __(sprintf("Listing Skip Row %d failed to validates:--- $limit .",$i), true); } else { echo "Welcome Amit....";} } if ($this->saveAll($data)) { // $return['errors'][] = __(sprintf("Listing Skip Row %d failed to save.",$i), true); }/*else { $return['messages'][] = __(sprintf('Listing for Row %d was saved.',$i), true); }*/ } fclose($handle); return $return; }