Php 如何从循环进程中获取文件计数,以便在循环之外的内容节中计数
我被卡住了。您将看到我有var*$file\u count\u header*。我只是想让这个数字和*file\u count*的计数一样增加(理想情况下只使用相同的变量)*$文件计数*在if()中按预期增加,但正如您所看到的,我的头内容不在循环中。通过将整个代码放入另一个循环中,我尝试了几种解决方案,但我无法让它继续工作Php 如何从循环进程中获取文件计数,以便在循环之外的内容节中计数,php,loops,while-loop,counter,Php,Loops,While Loop,Counter,我被卡住了。您将看到我有var*$file\u count\u header*。我只是想让这个数字和*file\u count*的计数一样增加(理想情况下只使用相同的变量)*$文件计数*在if()中按预期增加,但正如您所看到的,我的头内容不在循环中。通过将整个代码放入另一个循环中,我尝试了几种解决方案,但我无法让它继续工作 $results_count = mysql_num_rows($result); $i = 0; $file_count = 1; $per_file = 100; $f
$results_count = mysql_num_rows($result);
$i = 0;
$file_count = 1;
$per_file = 100;
$footer = 'FOOTER';
$default_contents = $contents = array("HEADER . $file_count_header");
while ($row = mysql_fetch_array($result)) {
// Build the line contents here
$line = $row['id'];
$contents[] = $line; // Each array element will be a line in the text file
$i++;
// Every $per_file number of records, write the contents to the file and start counting over
if ($i == $per_file) {
$contents[] = $footer; // Add the footer to the end
file_put_contents($results_count .'-'. $file_count .'.txt', implode("\r\n", $contents));
// Reset the counter and set the contents to the
$i = 0;
$contents = $default_contents;
$file_count++;
$file_count_header++;
}
}
// Output the rest of the contents to the last file
$contents[] = $footer; // Add the footer to the end
file_put_contents($results_count .'-'. $file_count .'.txt', implode("\r\n", $contents));
初始化
$file_count_header = 1;
顶部带有$file\u count
类似
$file_count = 1;
$file_count_header = 1
您遇到了一个问题,因为您没有初始化
$file\u count\u header
,甚至它只在中而时使用。所以它应该在之外声明,而使用默认值。我应该注意到我也尝试过,但它不起作用。同样的结果。计数不变。例如,如果我初始化$file\u count\u header=1;它在所有标题中都是1,没有计数差异。它应该是。你能用我说的更改来更新你的代码吗。如果$file\u count
增加,则$file\u count\u header
也必须增加。您可以显示您使用的变量的输出或使用var\u dump($file\u count\u header)代码>循环完成后。您是正确的,但$default\u contents=$contents=array(“HEADER.$file\u count\u HEADER”);未在每次迭代中使用正确的计数进行更新,因为它是在循环之前加载的,并且在循环期间未更改。是否在$default\u contents=$contents=array(“header.$file\u count\u header”)之前获取$file\u header
的值代码>行?如果是,则在此处显示var\u dump($file\u count\u header)代码>值;好啊在增加$file\u count\u header++的值之后,也尝试将其放入循环中代码>类似循环中的“回声”:;变量转储($file\u count\u header);回声“
”代码>然后您可以看到到底发生了什么。因为如果在代码顶部声明$file\u count\u header
,则必须在循环内和循环外都可以访问它。