【发布时间】:2017-01-31 16:24:22
【问题描述】:
我正在使用一个插件,它想在 javascript 中输入这样的数组:
var data = [
{
"id": 1,
"name": "University1",
"list": [
{"id": 1, "name": "Dorms", "list":
[
{"id": 1, "name": "Dorm1"},
{"id": 2, "name": "Dorm2"}
]
},
{"id": 2, "name": "Off-Campus", "list":
[
{"id": 1, "name": "North Campus"},
{"id": 2, "name": "East Campus"}
]
}
]
},
{
"id": 2,
"name": "University2",
"list": [
{"id": 1, "name": "Dorms", "list":
[
{"id": 1, "name": "Dorm1"},
{"id": 2, "name": "Dorm2"}
]
},
{"id": 2, "name": "Off-Campus", "list":
[
{"id": 1, "name": "North Campus"},
{"id": 2, "name": "East Campus"}
]
}
]
}
];
我的数组数据位于 SQL 数据库中。我无法在 php 中形成这个多维数组和/或使用 AJAX 传递它。
我的 javascript/jquery:
var locationsArray;
$.post(
'ajax/locationDropdown.php',
{
//NO DATA THIS TIME
},
function (response) {
console.log(response);
parseResponse = $.parseJSON(response);
var locationsArray = $.map(parseResponse, function(value, index) {
return [value];
});
console.log(locationsArray);
}
);
我的 php:
<?php
include 'databaseConnection.php';
$sqlLD1 = '
SELECT DISTINCT school
FROM timeBlocks
ORDER BY school ASC;
';
if (!$resultLD1 = $connection->query($sqlLD1)) {
die ('There was an error running the queryLD1 [' . $connection->error . ']');
}
$locationArray = array(
'id'=>array(),
'name'=>array(),
'list'=>array(
'id'=>array(),
'name'=>array(),
'list'=>array(
'id'=>array(),
'name'=>array()
)
)
);
$i=0;
while ($rowLD1 = $resultLD1->fetch_assoc()) {
$school = $rowLD1["school"];
$locationArray[$i][name] = $school;
$sqlLD2 = '
SELECT DISTINCT timeBlockLocation
FROM timeBlocks
WHERE school = "'.$rowLD1["school"].'"
ORDER BY timeBlockLocation ASC;
';
if (!$resultLD2 = $connection->query($sqlLD2)) {
die ('There was an error running the queryLD2 [' . $connection->error . ']');
}
$j=0;
while ($rowLD2 = $resultLD2->fetch_assoc()) {
$timeBlockLocation = $rowLD2["timeBlockLocation"];
$locationArray[$i][$j][name]=$timeBlockLocation;
$sqlLD3 = '
SELECT DISTINCT timeBlockSubLocation
FROM timeBlocks
WHERE school = "'.$rowLD1["school"].'"
AND timeBlockLocation = "'.$rowLD2["timeBlockLocation"].'"
ORDER BY timeBlockSubLocation ASC;
';
if (!$resultLD3 = $connection->query($sqlLD3)) {
die ('There was an error running the queryLD2 [' . $connection->error . ']');
}
$k=0;
while ($rowLD3 = $resultLD3->fetch_assoc()) {
$timeBlockSubLocation = $rowLD3["timeBlockSubLocation"];
$locationArray[$i][$j][$k][name]=$timeBlockSubLocation;
$k++;
}
$j++;
}
$i++;
}
echo json_encode($locationArray);
?>
这会产生一个如下所示的数组:
{
"0": {
"0": {
"0": {
"name": "All Locations"
},
"name": "Off Campus"
},
"1": {
"0": {
"name": "Dorm1"
},
"1": {
"name": "Dorm2"
}
"name": "Dorms"
},
"name": "University1"
},
"1": {
"0": {
"0": {
"name": "All Locations"
},
"name": "Off-Campus"
},
"1": {
"0": {
"name": "Dorm1"
},
"name": "Dorms"
}
"name": "University2"
},
"id": [],
"name": [],
"list": {
"id": [],
"name": [],
"list": {
"id": [],
"name": []
}
}
}
【问题讨论】:
标签: javascript php jquery sql arrays