2011-10-24 107 views
0

对于打开的购物车,我使用CSV导入插件,默认情况下,如果缺少任何列字段,则会完全跳过产品。 是否有无论如何我可以读取文件,并用'空'或0替换所有空字段,并将其发送回代码。用某些东西替换空的CSV值 - PHP

跳过下面的检查会导致阅读/放置格式发生偏移!

$fh = fopen($file, 'r'); 
    if(!$fh) die('File no good!'); 

    // Get headings 
    $headings = fgetcsv($fh, 0, $delim); 
    $num_cols = count($headings); 
    $num_rows = 0; 

    //Read the file as csv 
    while (($row = fgetcsv($fh, 0, $delim)) !== FALSE) { 

     //missed product if num columns in this row not the same as num headings 
    if (count($row) != $num_cols) { 
     $this->total_items_missed++; 
     continue; 
     } 


     for ($i=0; $i<count($headings); $i++) { 
      $raw_prod[$headings[$i]] = $row[$i]; 
     } 
+1

删除执行检查的4行,具体取决于您对数据所做的操作,可能是您需要的。 – 2011-10-24 19:42:07

+0

只是在这里产生一个偏移,然后$ raw_prod [$ headings [$ i]] = $ row [$ i]; – Neo

回答

1

这两条线

$this->total_items_missed++; 
continue; 

$row = array_pad($row, $num_cols, 0); 

更换这将增加任何遗漏值0的

+0

谢谢,这很好!不确定以下哪一个更适合,我假设他们提供相同的结果。从来没有在自己使用array_pad – Neo

+0

你只能使用它,如果你删除列数检查真的......所以没有它不会工作,因为你想。阵列垫是您不得不记住的功能之一。我几乎没有使用过它自己 –

1

尝试

for($i = 0 ; $i<count($headings) ; $i++){ 
    if(!empty($row[$i])){ 
     $raw_prod[$headings[$i]] = $row[$i]; 
    }else{ 
     $raw_prod[$headings[$i]] = 0;//or what ever value you want 
    } 
}