代码之家  ›  专栏  ›  技术社区  ›  Joe

仅将foreach循环中的前X个输出写入文件(关联数组内部)?

  •  0
  • Joe  · 技术社区  · 7 年前

    这是一个位于页面底部的“二级表”,其中只适合X个项目。我正在尝试只将前X项写入文件。

    复选框正在生成带有selection[]的$selection。

    $result = array();
    foreach( array_rand($selections, count($selections)) as $k ) {
    include dirname(__FILE__) . "/bottomfeature.php";
    }
    

    请注意,此循环正在使用其他文件,而不仅仅是bottomfeature.php。

    $featuretitle =  $result[] = $selections[$k];
    
    $featurearray = array(
    "<tr>",
    "<td>$featuretitle</td>",
    "</tr>"
    );
    $feature = implode("\n",$featurearray);
    
    $fp = fopen("bottomfeature.txt", "a");
    fwrite($fp, $feature);
    fclose($fp);
    

    另外,只写第一个输出怎么样?我试着在fopen中使用“w”。

    $fp = fopen("bottomfeature.txt", "w");
    

    但它只写入循环的最后一项,而不是第一项。

    谢谢你的帮助。

    使用html复选框更新

    <?php
    
    if(isset($_REQUEST['submit'])) {
    
    $result = array();
    foreach( array_rand($selections, count($selections)) as $k ) {
    include dirname(__FILE__) . "/bottomfeature.php";
    }
    
    }
    
    ?>
    
    <form action="" method="post">
    <input type="checkbox" name="selection[]" value="Brand1">Brand1</label>
    <input type="checkbox" name="selection[]" value="Brand2">Brand2</label>
    <input type="checkbox" name="selection[]" value="Brand3">Brand3</label>
    <input type="checkbox" name="selection[]" value="Brand4">Brand4</label>
    <input type="submit" name="submit" value="Save Setup" />
    </form>
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   mickmackusa Tom Green    7 年前

    在foreach循环中,只需使用索引就可以访问从0开始的计数器,这样就不用手动递增计数器。

    include可以引用计数器及其条件块中的限制,以确定是否应更新文件。其他进程可以在所有提交的值上运行。

    https://3v4l.org/I6bnC

    $limit = 4;
    $selections = ['a', 'b', 'c', 'd', 'e'];
    shuffle($selections);
    foreach ($selections as $i => $selection) {
        echo "before include $selection\n";
        // start include code...
            if ($i < $limit) {
                echo "**display limited $selection**\n";
            }
        // end include code
        echo "after include $selection\n";
        echo "---\n";
    }
    

    输出:

    before include d
    **display limited d**
    after include d
    ---
    before include b
    **display limited b**
    after include b
    ---
    before include a
    **display limited a**
    after include a
    ---
    before include c
    **display limited c**
    after include c
    ---
    before include e
    after include e
    ---
    

    $featurearray = array(
    "<tr>",
    "<td>$featuretitle</td>",
    "</tr>"
    );
    $feature = implode("\n",$featurearray);
    

    因为 $featurearray 在每次迭代时声明为单个元素数组(它不断被覆盖),使用的更好的数据类型是 string 而不是 array . 因为只有一个元素 \n

    我不建议对文件进行迭代修改。一个更好/更有效的过程是准备新数据,然后在循环完成后将其写入文件。我建议重新设计您的脚本。