-1

Hey guys I have the following:

for($i; $i< count($nontimedif); $i++){      
    $data[$i] = array(
      "Driver Chose Non-Compliance:" => $nontimedif[$i] . ", 
      " . $nonfirstname[$i]. ", 
      " . $nonlastname[$i]. ", 
      " . $nonemail[$i]. ", 
      " . .......
    );
}

so after this runs I want to add a few new rows because this than transfers into a .csv file. So how do I go about adding at the end of this?

How I am making the .csv file:

function cleanData(&$str)
  {
   // escape tab characters
    $str = preg_replace("/\t/", "\\t", $str);

    // escape new lines
    $str = preg_replace("/\r?\n/", "\\n", $str);

    // convert 't' and 'f' to boolean values
    if($str == 't') $str = 'TRUE';
    if($str == 'f') $str = 'FALSE';

    // force certain number/date formats to be imported as strings
    if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
      $str = "'$str";
    }

    // escape fields that include double quotes
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';

  }

// filename for download
  $filename = "website_data_" . date('Ymd') . ".xls";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");

  $flag = false;
  foreach($data as $row) {
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "\r\n";
      $flag = true;
    }
     array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)) . "\r\n";
  }
nickb
  • 59,313
  • 13
  • 108
  • 143
David Biga
  • 2,763
  • 8
  • 38
  • 61
  • Use this post to make an .csv file from an array: http://stackoverflow.com/questions/4249432/export-to-csv-via-php – S.Visser Apr 16 '13 at 20:25

3 Answers3

8
$data[] = array( 'Key:' => 'Whatever you want to add');
nickb
  • 59,313
  • 13
  • 108
  • 143
2

Use array_push

$additionalRow = array( 'Whatever'.'whatever'.$somethingelse);
array_push($data, $additionalRow);

Or, you can do this:

$headers = array_keys($data);
$lastKey = array_pop($data);
$lastKey++;
$data[$lastKey] - $additionalRow;

Good luck! Hope this helped!

antjanus
  • 987
  • 3
  • 15
  • 30
0

array_push can be a good solution for this situation where key is not known. You can check this http://php.net/manual/en/function.array-push.php

Biswajit Maji
  • 869
  • 13
  • 23