php – 如何从我的特定SQL查询中返回json?

我有以下
PHP代码:

<?php
$servername = "host";
$username = "user";
$password = "passw";
$dbname = "dbname";

$conn3 = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

$conn3->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$q3 = $conn3->prepare("SELECT c.one, c.two FROM table c");
    $q3->execute();
if($q3->rowCount()>0)
{
    $check3 = $q3->fetchAll(PDO::FETCH_ASSOC);
    $arr = array();
    foreach ($check3 as $row) {
    $arr[] = $row;
     //how can I return json format here?
    }   
}
$conn2 = null;
?>

并且此查询返回元素对.但是我如何修改上面的代码以获得元素的json格式:

{key1:OSO; key2:AIKA}等

这样我以后可以在jquery文件中使用它来打印它,具有以下功能:

$.getJSON('list.php', function(json) {
    //assuming list.php resides with list.html directory
    //console.log(json)
      console.log(json.result.key1);
       console.log(json.result.key2);

    });

谢谢!

最佳答案 更改

SELECT c.one, c.two FROM table c

SELECT c.one as key1, c.two as key2 FROM table c

然后将结果封装在json中(在foreach之后):

echo json_encode(array(
    'result'=>$arr
));

但是你很可能需要在jquery中循环使用它们.
你的json输出将是这样的:

result: [
    {'key1': 'asd', 'key2': 'qwe'},
    [...]
    {'key1': 'asd', 'key2': 'qwe'}
]

像他们一样循环他们:

//first, see how it looks:
console.log(json.result);
jQuery.each( json.result, function( i, subresult ) {
    console.log(subresult);
    // you should be able to use: subresult.key1
});
点赞