【问题标题】:PHP MySQL associative array using array_pushPHP MySQL关联数组使用array_push
【发布时间】:2013-02-10 09:27:15
【问题描述】:

我正在尝试使用 PHP 创建一个关联数组。我正在使用调用 json 文件的 ajax 脚本。

我已经使用以下 PHP 代码测试了脚本:

$testLocs = array(
'loc5' => array( 'info' => 'Some random info', 'lat' => 0, 'lng' => 60 ),
'loc6' => array( 'info' => 'Some random info', 'lat' => 0, 'lng' => 40.345 )
);
echo json_encode($testLocs);

哪个回响:

{"loc1":{"info":"Some random info","lat":0,"lng":60},"loc1":{"info":"Some random info","lat":0,"lng":40.345}}

ajax 代码将正常工作。现在我正在尝试编写一个 PHP 脚本来从数据库中获取信息。我的PHP代码如下

$query = "Select * from table";
$result = mysql_query($query);

$json_data = array();

while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$lat = $row['lat'];
$lon = $row['lon'];
$page = $row['page'];
array_push($json_data, array('info' => 'Some random info', 'lat' => $lat, 'lng' => $lon)); 
}


echo json_encode($json_data);

哪个回响:

{"info":"Some random info","lat":"-31.9522","lng":"115.8614"},{"info":"Some random info","lat":"40.7842","lng":"-73.8422"}

我不知道如何将'loc' => 放在每个数组的前面。 ajax 使用 locNUM 作为唯一 ID。

谢谢

【问题讨论】:

  • mysql_* 更改为 mysqliPDO?

标签: php mysql ajax json


【解决方案1】:

试试

$json_data = array();
$i = 0;

while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$lat = $row['lat'];
$lon = $row['lon'];
$page = $row['page'];
$json_data["loc" . ($i++)] = array('info' => 'Some random info', 'lat' => $lat, 'lng' => $lon); 
}

而不是array_pusharray_push 表示纯数组函数,而不是哈希操作函数。

【讨论】:

  • 谢谢它现在有效。我看过一个教程如何做到这一点,但后来我在数组中有数组。
【解决方案2】:

如果$row['id'] 是 locNUM 的唯一 ID:

$json_data["loc".$id] = array('info' => 'Some random info', 'lat' => $lat, 'lng' => $lon)

array_push()$array[] = $var; 相同,后者为您提供递增的数字键。

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 1970-01-01
    • 2011-08-13
    • 2016-10-07
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多