【问题标题】:For loops to open a file that has to variable in the nameFor 循环打开一个名称必须可变的文件
【发布时间】:2016-01-02 12:41:29
【问题描述】:

您好,我可能有一个非常愚蠢的问题。

我得到的是编写 json 文件的代码,在文件名中它会自动添加到递增数字的变量中。我想编写打开文件并将数据写入网页的代码。打开filename(1)(1).json 的文件有效,但没有其他文件打开。

这是创建文件的代码。

$Array = array("User Index" => $UniqueIndex,"User Name" => $UniqueUserName,"Submition Index" => $SubmitionCount,"Time & Date" => $TimeDate,"Submition" => $_POST["submition"]);
$ArrayWrite = fopen("forumdata/forumsubmition/ForumSubmition($UniqueIndex)($SubmitionCount).json", "w");
fwrite($ArrayWrite, json_encode($Array));
fclose($ArrayWrite);

这是尝试打开文件的代码。

for ($Count = 0; $Count <= $blarg; $Count += 1)    
    for ($Count2 =0; $Count2 <= $blarg2; $Count2 += 1)
        if (file_exists("forumdata/forumsubmition/ForumSubmition($Count2)($Count).json"))
        {
            do
            {
                $ForumInfo = file_get_contents("forumdata/forumsubmition/ForumSubmition($Count2)($Count).json", "r");
                $ForumInfo2 = json_decode($ForumInfo, true);

                if ($ForumInfo2["Submition"] != null)
                    foreach($ForumInfo2 as $value)
                        echo "$value<br>";
            }
            while (file_exists($ForumInfo));
        }

【问题讨论】:

  • 请更改您的变量名称。他们至少应该是驼峰式
  • 您对 content 和文件是否存在的问题 (while(file_exists($ForumInfo))) 使用相同的变量 ForumInfo。这不会按预期工作。此外, for 循环周围的大括号在哪里?
  • @Jan for 循环不需要大括号,因为后面只有一个语句 - 固定格式以便更清晰

标签: php arrays json for-loop


【解决方案1】:

当你有 2 个循环文件​​的 for 循环时,你为什么还要有 Do While 循环? 只需这样做:

for ($count = 0; $count <= $blarg; $count += 1)    
    for ($count2 =0; $count2 <= $blarg2; $count2 += 1)
        if (file_exists("forumdata/forumsubmition/ForumSubmition($count2)($count).json"))
        {
                $forumInfo = file_get_contents("forumdata/forumsubmition/ForumSubmition($count2)($count).json", "r");
                $formattedForumInfo = json_decode($forumInfo, true);

                if ($formattedForumInfo["Submition"] != null)
                    foreach($formattedForumInfo as $value)
                        echo "$value<br>";
        }

我还将您的变量格式化为骆驼大小写而不是帕斯卡大小写。

您不应该使用 do..while 循环的原因是因为您已经有第二个 for 循环遍历所有 $blarg2 计数。然后你有一个if 构造来检查文件是否存在。这应该足够了。无需再次检查。因为如果它不存在,它只会跳过它并进入第二个 for 循环中的下一个计数。

【讨论】:

  • 谢谢这是更好的代码。它没有解决我的主要问题文件名创建是在 2 个变量 $UniqueIndex 和 $SubmitionCount 上设置的,UniqueIndex 是分配给用户的索引号,可以是从 1 到 ∞ 的任何东西,submitioncount 是附加到文本的索引号用户输入的输入,也可以是从 1 到 ∞ 的任意值。所以我需要它能够使用该组合打开任何文件 ForumSubmition(1 to ∞)(1 to ∞).json 这可能很简单,但我看不到。
  • 忽略我最后的评论。它确实解决了我现在可以继续进行的这个项目的下一部分的所有问题。谢谢
  • 太棒了,如果你把答案标记为我的,那就太棒了;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多