我正在尝试使用PHP复制这个json文件,但我似乎无法获取对象的数组" location"在另一个名为" levels"
的数组中"levels": [
{
"id": "lower",
"title": "Floor 26",
"map": "images/apartment/upper.jpg",
"minimap": "images/apartment/upper-small.png",
"locations": [
{
"id": "1",
"title": "Kitchen",
"about": "",
"description": "<img src=\"images/logo.png\"
alt=\"sdfsfs\"><p>aaaaaaaaaaaaaa<p>",
"category": "furniture",
"x": "0.4746",
"y": "0.2883",
"zoom": "1"
},
这是我到目前为止所拥有的。
$connect1 = new mysqli("localhost", "root", "root", "location");
$result1 = mysqli_query($connect1, "SELECT * FROM locations");
$connect2 = new mysqli("localhost", "root", "root", "Floors");
$result2 = mysqli_query($connect2, "SELECT * FROM levels");
$data = array();
$levels = array();
while($row = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
$levels[] = $row;
}
$data["levels"] = $levels;
$locations = array();
while($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)){
$locations[] = $row;
}
$data["locations"] = $locations;
这是输出
"levels": [
{
"id":"1",
"title":"Floor26",
"map":"images\/apartment\/upper.jpg",
"minimap":"images\/apartment\/upper-small.png"
}
],
"locations": [
{
问题是我希望locations
成为json文件中显示的级别类别中的数组,而不是在插入数据后关闭levels
数组。请帮忙。我是一个完全的初学者,所以任何建议都将受到赞赏。
答案 0 :(得分:0)
首先,使用更多描述性变量名称。它们更容易阅读和理解。
其次,在嵌套循环中将位置添加到levels数组:
编辑:实际上,您不需要嵌套循环,因为每个级别的位置都相同。如果您每次都在查询不同的位置,或者根据级别更改导入的位置,那么嵌套就有意义了。
$locationConnect = new mysqli("localhost", "root", "root", "location");
$locationsResult = mysqli_query($locationConnect, "SELECT * FROM locations");
$levelsConnect = new mysqli("localhost", "root", "root", "Floors");
$levelsResult = mysqli_query($levelsConnect, "SELECT * FROM levels");
$data = array();
$levels = array();
$locationsArray = array();
//actually since locations appear to be the same for all results, you don't need to nest the loops, this is more efficient:
//loop location results and build locations array:
while($locationRow = mysqli_fetch_array($locationResult, MYSQLI_ASSOC)){
$locationsArray[] = $locationRow;
}
while($levelRow = mysqli_fetch_array($levelsResult, MYSQLI_ASSOC)){
//add locations array to your level row:
$levelRow["locations"] = $locationsArray;
//add level row to your levels array
$levels[] = $levelRow;
}
$data["levels"] = $levels;
//are you using this for something else? $employee_data seems to be a new array
$employee_data["locations"] = $locationsArray;