【问题标题】:Generating an array of JSON in PHP using a loop使用循环在 PHP 中生成 JSON 数组
【发布时间】:2016-03-08 00:29:14
【问题描述】:

一直在看这个,它似乎很简单,但由于某种原因我无法掌握它。

我现在的代码输出如下:

{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes1"}
{"society_id":2,"name":"TestName2","email":"Test@email2","description":"TestDes2"}

但我需要是这样的:

[{"society_id":1,"name":"TestName1","email":"Test@email1","description":"TestDes1"},
{"society_id":2,"name":"TestName2","email":"Test@email2","description":"TestDes2"}]

有人能指出我正确的方向吗?我对 PHP 很陌生。

<?php

    $user = 'root';
    $pass = '';
    $db = 'uopuser';

    $con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');


    $statement = mysqli_prepare($con, 'SELECT * FROM society');
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $society_id, $name, $email, $description);

$society = array();

while(mysqli_stmt_fetch($statement)){
    $society['society_id'] = $society_id;
    $society['name'] = $name;
    $society['email'] = $email;
    $society['description'] = $description;
    echo json_encode($society);
}

echo json_encode($society);

    mysqli_stmt_close($statement);

    mysqli_close($con);
?>

【问题讨论】:

    标签: php sql json


    【解决方案1】:

    你需要一个二维数组。本质上是一个“数组数组”。

    有关更多信息,请参阅示例 here

    $society = array();
    
    while(mysqli_stmt_fetch($statement)){
        $society[] = array(
            'society_id'  = $society_id,
            'name'        = $name,
            'email'       = $email,
            'description' = $description
        );
    }
    
    echo json_encode($society);
    

    【讨论】:

      【解决方案2】:

      对于您所需的 json 格式,您需要使用多维数组。并且无需在while() 循环内使用json_encode()

      示例

      $society = array();
      $key = 0;
      while(mysqli_stmt_fetch($statement))
      { 
          $society[$key]['society_id'] = $society_id; 
          $society[$key]['name'] = $name;
          $society[$key]['email'] = $email;
          $society[$key]['description'] = $description; 
          $key++;
      }
      echo json_encode($society); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-23
        • 1970-01-01
        • 2012-02-24
        • 2014-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多