【问题标题】:Create a Json array in a for loop - php在 for 循环中创建 Json 数组 - php
【发布时间】:2013-01-10 05:39:34
【问题描述】:
<?php
include '../connection.php';

$sql="SELECT userid,name,batch FROM dbusers";
$results=mysql_query($sql) or die("Cannot execute query");
$count=mysql_num_rows($results);
$arr=array();
for($i=0; $i < $count; $i++){
$rows=mysql_fetch_array($results);
//What to put here ?
}
json_encode($arr);

?>

这是我的 php 代码。我想问在 for 循环中放什么,以便我可以在 php 中创建一个数组数组。内部数组将包含用户 ID、名称和批次作为其元素。

【问题讨论】:

    标签: php loops arrays


    【解决方案1】:

    这里放什么?

    $arr[] = $rows;

    完整代码

    <?php
    include '../connection.php';
    
    $sql="SELECT userid,name,batch FROM dbusers";
    $results=mysql_query($sql) or die("Cannot execute query");
    $count=mysql_num_rows($results);
    $arr=array();
    for($i=0; $i < $count; $i++){
        $rows=mysql_fetch_array($results, MYSQL_ASSOC);//use MYSQL_ASSOC so you wouldn't have duplicate data
        $arr[] = $rows;
    }
    $json = json_encode($arr);
    
    ?>
    

    【讨论】:

      【解决方案2】:
      <?php
      include '../connection.php';
      
      $sql     = "SELECT userid,name,batch FROM dbusers";
      $results = mysql_query($sql) or die("Cannot execute query");
      $arr     = array();
      
      while($rows = mysql_fetch_assoc($results)){
          $arr[] = $row;
      }
      echo json_encode($arr);
      
      ?>
      

      试试这个。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-16
        • 1970-01-01
        • 2017-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-25
        • 1970-01-01
        相关资源
        最近更新 更多