【问题标题】:PHP JSON foreach troublePHP JSON foreach 麻烦
【发布时间】:2013-09-01 11:23:51
【问题描述】:

我用这个 php 代码创建了一个 json 结构:

<?php
    include "../base.php";

            $STH = $DBH->prepare("SELECT * FROM customers");
            $STH->execute();

            $result = $STH->fetchall(PDO::FETCH_ASSOC);
            $rows = $STH->rowCount();

            $jsontext = "{";
            $jsontext .= "total: ".$rows.",";
            $jsontext .= "page: 0,";
            $jsontext .= "records: [";

            foreach($result as $key => $inner_arr) {
                $jsontext .= "{";
                foreach($inner_arr as $field_name => $field_value) {
                    $jsontext .= "{$field_name}: {$field_value}, ";
                }
                $jsontext .= "},";
            }

            $jsontext .= "]";
            $jsontext .= "}";
    echo json_encode($jsontext);
?>

主要问题是这一行$jsontext .= "{$field_name}: {$field_value}, ";

当我用“echo”打印整个脚本时,它可以工作。但是$jsontext .= 无法正常工作,我只收到“null”。

【问题讨论】:

  • json_encode 是一个将php数组转换为json字符串的函数,你不需要在foreach中做任何这些
  • 只需使用 echo $jsontext;

标签: php json foreach


【解决方案1】:

尝试使用 json_encode 内置函数

json_encode

【讨论】:

    【解决方案2】:

    感谢@Satya 和@keune。

    更改最后一行
    echo json_encode($jsontext);
    

    echo $jsontext;
    

    解决问题。

    【讨论】:

      【解决方案3】:

      尝试:

                  $STH = $DBH->prepare("SELECT * FROM customers");
                  $STH->execute();
      
                  $result = $STH->fetchall(PDO::FETCH_ASSOC);
                  $rows = $STH->rowCount();
      
                  $jsontext['total'] = $rows;
                  $jsontext['page'] = 0;
      
                  foreach($result as $key => $inner_arr) {
                      foreach($inner_arr as $field_name => $field_value) {
                          $jsontext['records'][][$field_name] = $field_value;
                      }
                  }
          echo json_encode($jsontext);
      ?>
      

      p。 s。我没有测试过。

      【讨论】:

        【解决方案4】:

        替换

        json_encode($jsontext);
        

        echo $jsontext;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-26
          • 1970-01-01
          • 1970-01-01
          • 2023-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-10
          相关资源
          最近更新 更多