我想从 MySQL 数据库中存储的(以及其他)数据构建一个数组。
我的代码就是这样:
<?php
// STUFF ABOUT CONNECTION TO DATABASE
// Informations about host, login and so on
$query = 'SELECT * FROM maj';
$dbquery = mysql_query($query);
// Parse the dbquery
$geojson = array(
'type' => "FeatureCollection",
'features' => $feature
);
while($row = mysql_fetch_assoc($dbquery)) {
$feature = array(
'location' => $row['location'],
'geometry' => array(
'type' => 'Point')
);
array_push($geojson, $feature);
}
// Return routing result
print_r($geojson);
?>
我得到以下数组(前两个元素):
Array
(
[type] => FeatureCollection
[features] =>
[0] => Array
(
[location] => Hollywood, CA
[geometry] => Array
(
[type] => Point
)
)
[1] => Array
(
[location] => Ventura County
[geometry] => Array
(
[type] => Point
)
)
)
但是我想获得一个包含该内容的数组(“features”内部也有一个数组):
Array
(
[type] => FeatureCollection
[features] => Array
(
[0] => Array
(
[location] => Hollywood, CA
[geometry] => Array
(
[type] => Point
)
)
[1] => Array
(
[location] => Ventura County
[geometry] => Array
(
[type] => Point
)
)
)
)
我该怎么办?
非常感谢!
最佳答案
初始化$feature
并将其作为对$geojson
的引用传递:
$feature = array();
$geojson = array(
'type' => "FeatureCollection",
'features' => &$feature
);
删除 array_push()
并将其追加分配给 $feature
:
while($row = mysql_fetch_assoc($dbquery)) {
$feature[] = array(
'location' => $row['location'],
'geometry' => array(
'type' => 'Point')
);
// the above is sugar for: array_push($feature, array( 'location' => ... ) );
}
您对 print_r()
的调用应该会产生您现在期望的结果。
关于PHP : create a specific array from MySQL database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25463567/