【发布时间】:2015-05-15 15:00:56
【问题描述】:
我认为我正在处理的 PHP 页面可能存在语法问题,但尽管测试了多种方法,但我似乎无法破解这个问题。
对于上下文,我有一个页面查询 MySQL 数据库并获取一组部门名称和每个部门的三台服务器(Mac、Windows 和 Linux)的主机名。一旦有了这些数据,它就会调用一个函数,该函数使用这些主机名来获取关于每个服务器的更具体的数据集(比如说通过其他 MySQL 查询、CURL 等),并将每个部门服务器的数据添加到一个数组中。理想情况下,我试图将数组打印为 JSON 数据,但让所有 JSON 数据成为一个主数组的一部分。一切正常,除了 JSON 数据将每个数组分成自己的实体;
{
"department": "Math",
"macOS": "10.10.3",
"macRAM": "64GB",
"windowsOS": "2012.2",
"windowsRAM": "128GB",
"linuxOS": "5.5.1",
"linuxRAM": "32GB",
}
{
"department": "Science",
"macOS": "10.9.5",
"macRAM": "64GB",
"windowsOS": "XP",
"windowsRAM": "128GB",
"linuxOS": "1.2.3",
"linuxRAM": "32GB",
}
如上所述,所呈现的 JSON 数据不是用逗号分隔的,而是嵌入在括号中。我希望;
[
{
"department": "Math",
"macOS": "10.10.3",
"macRAM": "64GB",
"windowsOS": "2012.2",
"windowsRAM": "128GB",
"linuxOS": "5.5.1",
"linuxRAM": "32GB",
},
{
"department": "Science",
"macOS": "10.9.5",
"macRAM": "64GB",
"windowsOS": "XP",
"windowsRAM": "128GB",
"linuxOS": "1.2.3",
"linuxRAM": "32GB",
}
]
对不起,这里是我的 PHP 正在做所有的工作;
<?php
$data = array();
?>
<?php
$conn = mysqli_connect("localhost", "root", "root") or die('Error connecting to MySQLserver.');
mysqli_select_db($conn, "Database") or die("Failed to connect to database");
$sql = "SELECT * FROM Servers";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$department = $row['department'];
$serverMac = $row['serverMac'];
$serverWindows = $row['serverWindows'];
$serverLinux = $row['serverLinux'];
getData($department, $serverMac, $serverWindows, $serverLinux);
}
} else {
echo "Unable to connection to server. Please check your settings.";
}
?>
<?
function getData($serverMac, $serverWindows, $serverLinux) {
//Gather Data About Server Mac
//do something with the variable $serverMac
//Gather Data About Server Windows
//do something with the variable $serverWindows
//Gather Data About Server Linux
//do something with the variable $serverLinux
//Put The Gathered Data In An Array
$data = array('department' => $department,
'macOS' => $macOS,
'macRAM' => $macRAM
'windowsOS' => $windowsOS,
'windowsRAM' => $windowsRAM,
'linuxOS' => $linuxOS,
'linuxRAM' => $linuxRAM);
printData($data);
}
?>
<?php
function printData($data) {
echo "<pre>";
echo json_encode($data, JSON_PRETTY_PRINT);
echo "</pre>";
}
?>
任何帮助将不胜感激!谢谢!
【问题讨论】: