doudun3910 2015-12-08 22:58
浏览 37

从行转换为字符串(mysqli fetch_array)

I have a mysqli query that I want to convert to json.

tried:

$myArray = array();
while ($row = mysqli_fetch_array($result)) { 
    $myArray[] = $row;
}
$ot = json_encode($myArray);
print_r($ot); 

but got no results (blank line). If I print_r $myArray, there are values.

I can print out correct values on the while loop, so made another array and tried to add them, but neither of the following worked:

$mA []=array (alumnoX => $al1, grupox=> "two");
$mA []=array (alumnoX => (string)$al1, grupox=> "two");
$mA []=array (alumnoX => strval($al1), grupox=> "two");
$mA []=array (alumnoX => $row['alumno'], grupox=> "two");

How can I fix this?

edit -- (print_r of $myArray)

Array ( 
    [0] => Array ( 
              [0] => Martín 
              [alumno] => Martín 
              [1] => 1A 
              [grupo] => 1A 
              [2] => Computación básica 
              [materia] => Computación básica 
              [3] => sala cómputo cs 01 
              [salon] => sala cómputo cs 01 
              ) 
     [1] => Array ( 
              [0] => Martín 
              [alumno] => Martín 
              [1] => 1A 
              [grupo] => 1A 
              [2] => Introducción a la música 
              [materia] => Introducción a la música 
              [3] => Auditorio [salon] => Auditorio 
              ) 
      ) 
  • 写回答

2条回答 默认 最新

  • dongshang1768 2015-12-08 23:20
    关注

    When using mysqli_fetch_array() will return an associative array and a numerically indexed array, which will duplicate all columns and confuse you and the json object. So use either mysqli_fetch_array($result,MYSQLI_ASSOC) or mysqli_fetch_assoc($result) so you only get the more useful associative array returned.

    // assume you have code something like this
    $result = mysql_query($con, $sql);
    if ( ! $result ) {
        echo mysqli_error($con);
        exit;
    }
    
    
    $myArray = array();
    
    //while ($row = mysqli_fetch_array($result)) { 
    while ($row = mysqli_fetch_assoc($result)) { 
        $myArray[] = $row;
    }
    $ot = json_encode($myArray);
    
    //print_r($ot); print_r() works on arrays and $ot is now a string
    echo "<pre>$ot</pre>";
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制