JSON foreach循环将数据两次写入文件

时间:2018-09-26 14:54:44

标签: php json

我试图根据结果中仅存在1行还是超过1行来不同地处理JSON响应。

但是,从结果中提取的数据被两次写入文件。

有人知道为什么吗?

**添加了**

$module = $_POST['module'];
// Get The Data
$json = file_get_contents($url);
$obj = json_decode($json);
$row = $obj->response->result->$module->row;
// Count Rows & Fields
$countRows = count($row);
$fields = $obj->response->result->$module->row;
if($countRows == 1)
{
    $row = $obj->response->result->$module->row;
    $countFields = count($row->FL);
    foreach($row as $r) 
    {
         $i = 0;
         foreach($row->FL as $data)
         {
             $i++;
             if($i != $countFields)
             {
                 $csvfile = $module.'.csv';
                 $file = fopen($csvfile, "a");
                 $write = $data->content.',';
                 fwrite($file, $write);
                 fclose($file);
            } 
            else 
            {
                $file = fopen($csvfile, "a");
                $write = $data->content.PHP_EOL;
                fwrite($file, $write);
                fclose($file);
            }
        }
    } 
} else {
        $row = $obj->response->result->$module->row;
        $countFields = count($row[0]->FL);
        foreach($row as $r) 
        {
            $i = 0;
            foreach($r->FL as $data)
            {
                $i++;
                if($i != $countFields)
                {
                $csvfile = $module.'.csv';
                $file = fopen($csvfile, "a");
                $write = $data->content.',';
                fwrite($file, $write);
                fclose($file);
                } else {
                $file = fopen($csvfile, "a");
                $write = $data->content.PHP_EOL;
                fwrite($file, $write);
                fclose($file);
                }
            }
        }
    } 
}

令我更加困扰的是我遇到了错误:

  

未定义的属性:stdClass :: $ content

这里

 $write = $data->content.',';

但是出于某种未知原因,它正在将数据写入文件两次

以上错误仅发生在仅返回1条记录的JSON结果上。

示例JSON结果

{
  "response": {
    "result": {
      "Deals": {
        "row": {
          "no": "1",
          "FL": [
            {
              "val": "DEALID",
              "content": "3508588000000206039"
            },

1 个答案:

答案 0 :(得分:1)

请注意,$row是对象而不是and数组(如您的示例所示)。

它具有2个字段:“否”和“ FL”。因此,当您使用foreach($row as $r)进行循环时,您将进行2次回合(在json对象上循环)。

因此,您现在两次执行内部范围检查。其中有:

foreach($row->FL as $data) // here referring to base $row
 ...
    $write = $data->content.',';

我建议像这样保留if ($countRows == 1)选项:

if($countRows == 1)
{
  $row = $obj->response->result->$module->row;
  $csvfile = $module.'.csv';
  $countFields = count($row->FL);
  $i = 0;
  foreach($row->FL as $data)
  {
      $i++;
      $file = fopen($csvfile, "a");
      $write = $data->content;
      if($i != $countFields)
          $write .= ',';
      else 
          $write .= PHP_EOL;
      fwrite($file, $write);
      fclose($file);
  }
}