【问题标题】:JSON loop gives one array more than expectedJSON 循环给出的数组比预期的多一个
【发布时间】:2016-04-26 11:03:01
【问题描述】:


我的 PHP 代码有一个奇怪的情况。
基本上我想输出我在一个目录中所有 JSON 文件的 JSON,但由于一个意想不到的原因,它给了我 两个 JSON 数组,一个是错误的,一个是正确的。
代码如下:

$files = glob("players/*");
$nFiles = count($files);

foreach($files as $file){

  $jsonArray[] = array(

    "name" => "a name",
    "reason" => "a reason",
    "date" => "a date"

  );

  echo json_encode($jsonArray);
}

输出:

[{"name":"a name","reason":"a reason","date":"a date"}] -- here the loop stops (idk why) and it begins again -- [{"name":"a name","reason":"a reason","date":"a date"},{"name":"a name","reason":"a reason","date":"a date"}]

【问题讨论】:

  • 也许您需要将您的echo 放在foreach 的右括号下
  • 该死!没看到。谢谢你,伙计

标签: php json web output


【解决方案1】:

您应该将 echo 语句放在 foreach 循环之外:

$files = glob("players/*");
$nFiles = count($files);

foreach($files as $file){

  $jsonArray[] = array(

    "name" => "a name",
    "reason" => "a reason",
    "date" => "a date"

  );
}
  echo json_encode($jsonArray);

【讨论】:

  • 是的,我没看到。
猜你喜欢
  • 1970-01-01
  • 2015-01-12
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多