dongshao1021 2016-03-04 10:32
浏览 68
已采纳

使用array_push追加到所需行的末尾(PHP)

So I'm trying to append a string at the end of a row. The row and the string is inputted by the user.

//irrelevant...
$row = $_POST["whichRow"];
$Comment = $_POST["stringValue"];

$lines = array();
$arrayWithComment = array(";", "$actualComment");
$lineCount = 0;

foreach(file('/var/www/html/bkbpNew/tickets.csv') as $line){    

if ($lineCount == $row){
        array_push($lines, $line, $arrayWithComment[0], $arrayWithComment[1]);}
    else{
        array_push($lines, $line);}

    $lineCount++;
}

file_put_contents('/var/www/html/bkbpNew/tickets.csv', $lines);

And that sort of works, but not in the way that I want it to. Here is the edited file before/after & the desired state:


(Input values for this example are comment = "test" and row = 2)

Desired result of edited file:

1;example;example;example;example;example;example
2;example;example;example;example;example;example;test
3;example;example;example;example;example;example

Edited file BEFORE the above code is executed:

1;example;example;example;example;example;example
2;example;example;example;example;example;example
3;example;example;example;example;example;example

Edited file AFTER the above code is executed:

1;example;example;example;example;example;example
2;example;example;example;example;example;example
;test3;example;example;example;example;example;example

it automatically goes into the next line (Desired result) but I don't want it to. How do I go about this? Cheers!

  • 写回答

1条回答 默认 最新

  • du548397507 2016-03-04 10:41
    关注

    when you use file(), newline characters are included at the end of the line, so when you're adding your new comment to the end of the line you're adding it after the new line character

    I'm not a big fan of your approach to this, but as a quick and dirty solution use the FILE_IGNORE_NEW_LINES flag for file(), and then manually re-add the newline characters for each line in your loop

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?