在php中使用Echo json数据进行数据表使用

时间:2016-09-02 10:57:25

标签: php arrays json datatable

我一直在尝试回显json数组数据,但是我收到了错误。我以前没有这样做过。我想将它用于数据表。

这是我试图做的,但它显示错误,但如果我复制返回文本并保存在php文件夹中它工作正常。我需要帮助来解决它。

<?php
try {
    $db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
    $db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $users_stmt = $db_conn->prepare("SELECT * FROM users");
    $users_stmt->execute();
    while ($row = $users_stmt->fetch(PDO::FETCH_ASSOC)){
        //json_encode($users_stmt->fetch(PDO::FETCH_ASSOC));
        $dataarray = '
            [
                "'.$row['username'].'",
                "'.$row['fullname'].'",
                "'.$row['email'].'",
                "'.$row['siteright'].'",
                "2011/04/25",
                "$320,800"
            ],
        ';

    }
} catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage();}

echo '{<br/>
    "data": [<br/>'
    .$dataarray.
    '<br/>[
      "Donna Snider",
      "Customer Support",
      "New York",
      "4226",
      "2011/01/25",
      "$112,000"
    ]<br/>
  ]<br/>
}';
?>

我希望它看起来像这样

{
  "data": [
    [
      "Tiger Nixon",
      "System Architect",
      "Edinburgh",
      "5421",
      "2011/04/25",
      "$320,800"
    ],
    [
      "Donna Snider",
      "Customer Support",
      "New York",
      "4226",
      "2011/01/25",
      "$112,000"
    ]
  ]
}

3 个答案:

答案 0 :(得分:2)

reference link JSON_PRETTY_PRINT

while ($row = $users_stmt->fetch(PDO::FETCH_ASSOC)){
$dataarray['data'][] = array(
                       $row['username'], $row['fullname'], 
                       $row['email'], $row['siteright'], 
                       2011/04/25, $320,800
                     );
}

 $json_data = json_encode($newData,JSON_PRETTY_PRINT);  

 echo $json_data;

答案 1 :(得分:0)

echo '<pre>';
print_r($jsonData);     //  instead of echo
echo '</pre>';

答案 2 :(得分:0)

我想你想这样做 -

while ($row = $users_stmt->fetch(PDO::FETCH_ASSOC)){
  $dataarray['data'][] = array(
                           $row['username'], $row['fullname'], 
                           $row['email'], $row['siteright'], 
                           2011/04/25, $320,800
                         );
}
$jsonData = json_encode($dataarray);

print_r($jsonData); // your json output