2013-10-09 113 views
1

我正在開發一個cron作業,讀取具有json格式的一些配置的配置文件,並且我還有一個csv文件,我必須將該數據插入到mysql tanaro中
I已完成其第一部分,即閱讀配置文件和閱讀csv文件
現在的問題是我必須在csv中搜索配置文件中的mysql列,然後如果在csv中發現匹配列,則必須插入從該列到MySQL表中的值。
我被這個部分卡住了,需要一些幫助來完成這個。
這是示例配置文件,我必須在csv中搜索源代碼,並且必須將其放入csv的d​​etination列。搜索csv列並插入到mysql

"matchingField": [ 
      { 
       "source": "ProductLongDescription", 
       "detination": "Description" 
      }, 
      { 
       "source": "ExtraTextOne", 
       "detination": "EventDate" 
      }, 
      { 
       "source": "ExtraTextTwo", 
       "detination": "EventTime" 
      }, 
      { 
       "source": "ExtraTextThree", 
       "detination": "LocationInfo" 
      }, 
      { 
       "source": "Zupid", 
       "detination": "Unique_ID" 
      }, 
      { 
       "source": "ProductName", 
       "detination": "Title" 
      }, 
      { 
       "source": "ProductPrice", 
       "detination": "Price" 
      }, 
      { 
       "source": "MerchantProductCategory", 
       "detination": "Category" 
      }, 
      { 
       "source": "ImageMediumURL", 
       "detination": "ExternalImageUrl" 
      }, 
      { 
       "source": "ProductManufacturerBrand", 
       "detination": "LocationName" 
      }, 
      { 
       "source": "ZanoxProductLink", 
       "detination": "RedirectLink" 
      }, 
      { 
       "source": "TermsOfContract", 
       "detination": "sittingType" 
      } 
     ] 
+0

您可以將整個csv文件存儲到一個數組,然後搜索數組? – joe42

+0

有沒有考慮過使用LESS這樣的東西來做到這一點? http://lesscss.org/ – Machavity

+0

你能給我寄一些幫助代碼嗎? – Shani

回答

0

得到了我自己的解決方案:)。首先爲源列和目標列創建兩個數組,然後爲csv頭列創建一個數組,然後在源數組中搜索頭列值,如果找到匹配,則創建一個包含目標列名稱和來自csv的相應值的查詢。可能b我沒有很好地解釋代碼,但是這解決了我的問題。

while (($data = fgetcsv($handle, 10000, $columnDelimiter)) !== FALSE) 
{ 
    $number_of_fields = count($data); 
    if ($current_row == 1) 
    { 
    //Header line 
     for ($c=0; $c < $number_of_fields; $c++) 
     { 
      $header_array[$c] = $data[$c]; 
     } 
    } 
    else 
    { 
    //Data line 
     $sql_str = ''; 
     for ($c=0; $c < $number_of_fields; $c++) 
     { 
      if($key = array_search($header_array[$c],$source_arr)){ 
       $sql_str .= $dest_arr[$key]." = '".$data[$c]."',"; 
      } 
     } 
     $sql_str = "INSERT INTO $destinationTable SET ".trim($sql_str,','); 
     mysql_query($sql_str); 
    } 
    $current_row++; 
}