简体   繁体   中英

How to format the retrieved MySQL data in JSON format using php

I am trying to retrieve data from MySQL using php but I am a bit new to php. I have a table like so

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

And I hope to retain a JSON like in this format:

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

My php script is like this:

<?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));
?>

But the output is row format (with repeated headers) and not exactly in the JSON format I desire and its reading 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]]

Thank you so much for the time!

You're creating a new object for each row, not adding them to arrays for each column.

Create a 2-dimensional array with elements for each column. Then when processing the query results, push each column onto the appropriate element array.

<?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);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM