如果当前值为空,则使用先前的数组值 - 从CSV读取

时间:2014-02-05 15:36:54

标签: php arrays csv replace

我有一个CSV文件,内容类似于以下内容:

"Red",Red Coat
"",Red Dog
"",Red Car
"Blue",Blue Stuff
"Green",Green Stuff
"",Green Grass

我可以阅读此内容并通过PHP输出。

if (($handle = fopen("file.csv", "r")) !== FALSE) {
$row=0;
$csv_row = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$csv_row = $data;

      $previous=$csv_row[0]
      $colour=$csv_row[0]
      if $colouris null then $colour=$previous;
      echo $colour." ".$csv_row[1]."<BR>";

}
fclose($handle);
}

这将显示输出与缺失项目的空白。

我不是开发人员所以原谅下面的问题和丑陋的逻辑。我希望将$ color的现有值用于下一个$ color,如果它是空白的。

类似于:

      $previous=$csv_row[0]
      $colour=$csv_row[0]
      if $colour is null then $colour=$previous;

所以我的CSV会告诉我:

 Red Red Coat
 Red Red Dog ( previously Colour was empty)
 Red Red Car ( previously Colour was empty)
 Blue Blue Stuff
 Green Green Stuff
 Green Green Grass ( previously Colour was empty)

任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

改变这个:

if $colour is null then $colour=$previous;

对此:

if (!$colour)
{
    $colour = $previous;
}

因此,如果$ color为null或为空,$ color将从$ previous获取值。

另外,我想你可能想改变这个:

$previous=$csv_row[0];
$colour=$csv_row[0];

对此:

$previous=$csv_row[0];
$colour=$csv_row[1];

答案 1 :(得分:1)

您只需在代码中更改少量内容即可。 $ previous变量不是必需的。

这有效 -

if (($handle = fopen("a.php", "r")) !== FALSE) {
$row=0;
$csv_row = array();

$color = "";
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $csv_row = $data;
    //Don't update $color if no color available.
    if($csv_row[0] != null){
        $color = $csv_row[0];
    }
    echo $color." ".$csv_row[1]."<BR>";
}
fclose($handle);
}

/*
OUTPUT:
Red Red Coat
Red Red Dog
Red Red Car
Blue Blue Stuff
Green Green Stuff
Green Green Grass
*/