JSON循环给出了一个比预期更多的数组

时间:2016-01-20 14:30:30

标签: php json web output


我的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"}]

1 个答案:

答案 0 :(得分:2)

您应该将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);
相关问题