我开始想知道我的头在哪里,因为我应该在粉碎上这个......
场景:
MySQL DB Table > 'Sites'
Columns > 'Siteid(INT)','Location(Varchar)','Address(varchar)','PostalCode(varchar)'...etc
尝试将所有行从表获取到 PHP 数组中,编码为 json。
我想通过sitesArray[Location]在javascript中访问这些数据。地址会给我123街
sitesArray[多伦多]> "地址" : '123 Street', '邮政编码' : '12345'
sitesArray[蒙特利尔]> "地址" : '0987 Street', '邮政编码' : '09876'
我可以从数据库获取所有行没有问题...但是我被困在这个爆炸阵列的事情上...我无法将其放入关联数组中...每当我从 mysql 编码直数组时,它都是无效的 json,此外,没有整数或文字索引......
PHP DB 到 ARRAY 到 JSON
$result = mysql_query("SELECT * from Recommendations.Satellite_Sites;");
while($row= mysql_fetch_array($result)){
$fullSiteDetails[$row['Site']] = array("site" => $row["Site"],"city" => $row["Site_City"], "address" => $row["Site_Address"], "postalcode" => $row["Site_PostalCode"], "phone"=>$row["Site_Phone"],"fax"=>$row["Site_Fax"]);
}
die(json_encode($fullSiteDetails));
这是我在数据库查找期间在 while 循环中构建的数组
$fullSiteDetails[] = array("site" => $row["Site"],"city" => $row["Site_City"], "address" => $row["Site_Address"], "postalcode" => $row["Site_PostalCode"], "phone"=>$row["Site_Phone"],"fax"=>$row["Site_Fax"]);
JSON json_encode($fullSiteDetails)....>
[
{
site: "Ajax",
city: "Ajax",
address: "xxx Salem Road, Unit xxx",
postalcode: "L1Z xxx",
phone: "(905)-xxx-xxxx",
fax: "(905)-xxx-xxxx"
},
{
site: "Cambridge",
city: "Cambridge",
address: "123 Street",
postalcode: "A4E xxx",
phone: "(519)-xxx-xxxx",
fax: "(519)-xxxx-xxxx"
},
{
site: "Mississauga",
city: "Mississauga",
address: "xxx Derry Road East, Suite xxx",
postalcode: "L5T xxx",
phone: "(905)-xxxx-xxxx",
fax: "(905)-xxx-xxxx"
},
{
site: "Ottawa",
city: "Ottawa",
address: "xxxxx Hunt Club Road, Unit xx",
postalcode: "xxx 0Y3",
phone: "(613)-xxx-xxxx",
fax: "(613)-xxx-xxxx"
},
{
site: "Sudbury",
city: "Sudbury",
address: "xxxx Elm Street, Suite xx",
postalcode: "xxx xxx",
phone: "(705)-xxx-xxxx",
fax: "(705)-xxx-xxxx"
},
{
site: "TWH",
city: "Toronto",
address: "xxxxxxxxxxxxxxxxxxxxxxxxx",
postalcode: "xxx xxx",
phone: "(416)-xxx-xxxx",
fax: "(416)-xxx-xxxx"
}
]
不仅密钥未被取消,而且我还想将其放入关联数组中......
在javascript中,我正在这样做:
var fullSiteDetails = {};
fullSiteDetails = '<?php echo json_encode($fullSiteDetails) ?>';
在控制台中:
fullSiteDetails[0]
"{"
fullSiteDetails[Ajax]
VM8497:2 Uncaught ReferenceError: Ajax is not defined
fullSiteDetails['Ajax']
undefined
我错过了什么或没有坚持什么?
谢谢你的时间。
在 PHP 代码中看不到列位置。但是要使其成为关联数组,只需用户如下:
$fullSiteDetails[$row["Site_City"]] = array(...
如果其中没有保留的js字,则实际上不需要引用键。
使用以下字符串将 php 数组获取到 js 对象。不要添加 ' 因为它是 alredy js 对象,不需要任何引用
var fullSiteDetails = <?php echo json_encode($fullSiteDetails) ?>;
也许您的数据中有'或'。如果您使用的是json_encode请尝试使用 JSON_HEX_APOS
和/或 JSON_HEX_QUOT
作为 2。参数。如果这不起作用,请尝试发布格式错误的 json