从mySQL中获取数据并通过php生成json,如下所示:
while ($row = mysql_fetch_array($result)) {
$menu[] = array("type"=>"FeatureCollection",
"features" => [array("type"=>"Feature",
"geometry"=>array("type"=>"Point",
"coordinates"=>[-77.034084142948,38.909671288923]),
"properties"=>array("phone"=>"041","city"=>"Faisalabad","country"=>"Pakistan"))]
);
} $json = json_encode($menu);
echo $json;
,结果如下:
[
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-77.034084142948,
38.909671288923
]
},
"properties": {
"phone": "041",
"city": "Faisalabad",
"country": "Pakistan"
}
}
]
},
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-77.034084142948,
38.909671288923
]
},
"properties": {
"phone": "041",
"city": "Faisalabad",
"country": "Pakistan"
}
}
]
},
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-77.034084142948,
38.909671288923
]
},
"properties": {
"phone": "041",
"city": "Faisalabad",
"country": "Pakistan"
}
}
]
}]
正如你所看到{“type”:“FeatureCollection”,“features”:[{...}]}正在重复三次,我希望它出现在开头,就像跟着json一样,所以{ “type”:“FeatureCollection”,“features”:[{I WANT LOOP HERE only}}}:我想要这个结果:
[
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-77.034084142948,
38.909671288923
]
},
"properties": {
"phone": "041",
"city": "Faisalabad",
"country": "Pakistan"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-77.034084142948,
38.909671288923
]
},
"properties": {
"phone": "041",
"city": "Faisalabad",
"country": "Pakistan"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-77.034084142948,
38.909671288923
]
},
"properties": {
"phone": "041",
"city": "Faisalabad",
"country": "Pakistan"
}
}
]
}]
请帮助我一直在尝试太多。感谢
答案 0 :(得分:1)
那么,为什么你要继续重复" FeatureCollection"在while循环中,如果你只需要一次?
我想你想要这样的东西:
$menu = array();
features = array();
$menu['type'] = 'FeatureCollection';
while ($row = mysql_fetch_array($result)) {
$features[] = array("type"=>"Feature",
//Other features here
);
}
$menu['features'] = $features;
答案 1 :(得分:1)
在$menu
数组中,您应该定义值为type
的键FeatureCollection
和键features
。在你的while循环中执行以下操作:
$menu = array(
'type' => 'FeatureCollection',
'features' => array()
);
while ($row = mysql_fetch_array($result)) {
$menu[`features`][] = array(...);
}