Справка по структуре массива в php для генерации json

0

Получение данных из mySQL и генерация json через php следующим образом:

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": [{Я ХОТЯ ЗАГРУЗИТЬ ЗДЕСЬ}}}: Я хочу получить этот результат:

[
{
    "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
    Если вы не хотите использовать массив так, как вы это делаете в настоящее время, измените создание массива в цикле while.
Теги:

2 ответа

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;
  • 0
    Спасибо за исправление
1

В вашем $menu массиве вы определяете type ключа со значением FeatureCollection и ключевые features. И в вашем цикле while сделайте следующее:

$menu = array(
    'type' => 'FeatureCollection',
    'features' => array()
);
while ($row = mysql_fetch_array($result)) {
    $menu['features'][] = array(...);
}
  • 0
    как насчет квадратных скобок, обертывающих это .. не хватает, как мне добавить это

Ещё вопросы

Сообщество Overcoder
Наверх
Меню