如何使用PHP将检索到的MySQL数据格式化为JSON格式

swiftleneneer

我正在尝试使用php从MySQL检索数据,但是我对php有点陌生。我有这样的桌子

    distance    height      time
         25      70       17:50:24
         12      69       17:30:24
         15      55       17:10:24

我希望保留这种格式的JSON:

{
    
      "data": true,
    
      "time":[
      "17:50:24",
      "17:30:24",
      "17:10:24"
    ],
    
      "distance":[
        25,
        12,
        15
      ],  
    
       "height":[
        70,
        69,
        55
      ]
    
    }

我的PHP脚本是这样的:

<?php  
$db = mysqli_connect("127.0.0.1", "root", "pw", "test1"); 
$row=$db->prepare('SELECT * FROM table');  
$row->execute();
$json_data=array();
$json_latdata=array();

$result = array();
$result1 = array();
foreach($row as $rec)//foreach loop  
{  
    $json_array['distance']=$rec['distance']; 
    $json_array['height']=$rec['height'];   
    $json_array['time']=$rec['time'];  
    array_push($json_data,$json_array); 
    array_push($json_latdata,$json_array1);   
}  
$result = $json_data;
$result1 = $json_latdata;
echo json_encode(array($result,$result1));
?>

但是输出是行格式(具有重复的标题),而不是我想要的JSON格式,并且其读数为null:

[[{"distance":null,"height":null,"time":null},
  {"distance":null,"height":null,"time":null},
  {"distance":null,"height":null,"time":null},
  {"distance":null,"height":null,"time":null},
  {"distance":null,"height":null,"time":null},
  {"distance":null,"height":null,"time":null},
  {"distance":null,"height":null,"time":null},
  {"distance":null,"height":null,"time":null},
  {"distance":null,"height":null,"time":null},
  {"distance":null,"height":null,"time":null}],
 [null,null,null,null,null,null,null,null,null,null]]

非常感谢您抽出宝贵的时间!

巴尔玛

您正在为每一行创建一个新对象,而不是将它们添加到每一列的数组中。

创建一个二维数组,其中每一列都有元素。然后,在处理查询结果时,将每一列推入适当的元素数组。

<?php  
$db = mysqli_connect("127.0.0.1", "root", "pw", "test1"); 
$stmt = $db->prepare('SELECT distance, height, time FROM table');  
$stmt->execute();
$rows = $stmt->get_result();

$result = ['data' => true, 'time' => [], 'distance' => [], 'height' => []];
foreach($rows as $rec)//foreach loop  
{  
    foreach ($rec as $col => $value) {
        $result[$col][] = $value;
    }
}  
echo json_encode($result);
?>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章