给一个JSON对象数组命名:到php



在这里我从 PHP 从 MYSQL 获取 JSON 数组作为字符串如何为数组 JSON 对象命名为这样。

{
"task":
[
{
"tid":"1",
"titls":"testing",
"uid":"1101",
"subject":"test",
"sp":"10",
"date":"2018-01-01"
},
{
"tid":"2",
"titls":"tesssting",
"uid":"1101",
"subject":"tesssst",
"sp":"11",
"date":"2018-01-01"
}
]
}

而这个php文件怎么能给数组JSON对象。

// an array to save the application data
$rows = array();
// iterate to query result and add every rows into array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row; 
}
// close the database connection
mysqli_close($con);
// echo the application data in json format
echo json_encode($rows);

要向 JSON 字符串添加名称,您可以尝试执行以下操作:

// an array to save the application data
$rows = array();
// iterate to query result and add every rows into array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row; 
}
// close the database connection
mysqli_close($con);
// echo the application data in json format
echo json_encode(array("task" => $rows));

我还建议您使用header('Content-Type: application/json');来指定您正在回复 JSON 数据,如果您计划在应用程序中使用它。

我尝试了这段代码,它对我有好处,这就是我想要的

header('Content-Type: application/json');
// echo the application data in json format
echo json_encode(array('task' => $rows), JSON_PRETTY_PRINT);

最新更新