提问人:macca4244 提问时间:5/31/2023 更新时间:5/31/2023 访问量:48
将 json 文本转换为 datatables 的 PHP 数组 childrow 示例 [duplicate]
Convert json text to PHP array for datatables childrow example [duplicate]
问:
我引用了这个数据表示例 https://datatables.net/examples/api/row_details.html 并尝试使用 PHP 生成示例中使用的 AJAX。
下面是原始 json 代码的片段。如果我将其粘贴到我的 Ajax php 代码中,它将在我的数据表上呈现正确的数据。
{
"data": [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "8422"
},
{
"id": "3",
"name": "Ashton Cox",
"position": "Junior Technical Author",
"salary": "$86,000",
"start_date": "2009/01/12",
"office": "San Francisco",
"extn": "1562"
}
]
}
我使用了一个 json 到 PHP 的转换工具来查看我应该用的正确格式编写它,但是当我将其添加到我的数据库循环中时,它只给了我数据表中的一行数据。我希望它能给我 3 行。我很确定这只是因为我如何初始化 $dataArray 变量,但不确定还能如何编写它。下面是我正在使用的PHP代码。
$sql1= "Select Top(3) * from Table where RouteStatus = 1";
$stmt1=sqlsrv_query( $mysq, $sql1);
$dataArray=array();
while( $row= sqlsrv_fetch_array( $stmt1, SQLSRV_FETCH_ASSOC) ) {
$dataArray=[
"data" => [
[
"id" => $row['RouteHeaderID'],
"name" => $row['BulkId'],
"position" => $row['Heigh'],
"salary" => "$320,800",
"start_date" => "2011/04/25",
"office" => "Edinburgh",
"extn" => "5421"
]
]
];
}
回声json_encode($dataArray);
答:
0赞
lezhni
5/31/2023
#1
您只需重写同一数组键的每一行,改用(添加新的子数组):[]
while($row = sqlsrv_fetch_array($stmt1, SQLSRV_FETCH_ASSOC)) {
$dataArray['data'][] = [
"id" => $row['RouteHeaderID'],
"name" => $row['BulkId'],
"position" => $row['Heigh'],
"salary" => "$320,800",
"start_date" => "2011/04/25",
"office" => "Edinburgh",
"extn" => "5421"
];
}
评论
0赞
mickmackusa
6/1/2023
请投票关闭新的重复问题,而不是回答它们。
评论