php中动态json数组出错

时间:2017-09-06 18:22:40

标签: php arrays json

我有一个应用程序从mysql数据库中检索数据并使用php生成一个json输出以发送到插件。

我正在从php生成以下json输出:

{
  "mapwidth":"1300",
  "mapheight":"1000",
  "categories":"[]",
  "levels":{
    "id":"lots",
    "title":"Lots",
    "map":"maps\/lot-map.svg",
    "minimap":"",
    "locations":[
      {
        "id":"lot1",
        "title":"Lot 1",
        "pin":"hidden",
        "description":"<p>Status: <b style=\\\"color: #8eba5e;\\\">Available<\/b><br>Size:\u00a0<b>850 sqm<\/b><br>Please get in touch for an Offer.<\/p>",
        "link":null,
        "x":"0.4849",
        "y":"0.4629",
        "fill":null,
        "category":"false",
        "action":"tooltip"
      }
    ]
  },
  "maxscale":"1.8"
}

但格式不正确。应该像下面测试的json文件一样:

{
    "mapwidth": "1300",
    "mapheight": "1000",
    "categories": [],
    "levels": [
        {
            "id": "lots",
            "title": "Lots",
            "map": "maps/lot-map.svg",
            "minimap": "",
            "locations": [
                {
                    "id": "lot12",
                    "title": "Lot 12",
                    "pin": "hidden",
                    "description": "<p>Status: <b style=\"color: #8eba5e;\">Available</b><br>Size: <b>850 sqm</b><br>Please get in touch for an Offer.</p>",
                    "link": "#more",
                    "x": "0.3726",
                    "y": "0.4565"
                }
            ]
        }
    ],
    "maxscale": 1.8
}

区别在于“关卡”键。

这是我的PHP代码:

   $results = array(
                'mapwidth' => '1300',
                'mapheight' => '1000',   
                'categories' => '[]'
            ); 

    $results['levels'] = array(
                'id'   => 'lots',
                'title'  => 'Lots',
                'map' => 'maps/lot-map.svg',
                'minimap' => ''
            ); 

    if ($lotes)
    {
        // build usable array
        foreach($lotes['results'] as $lote)
        {

            $results['levels']['locations'][] = array(
                'id'   => $lote['slug'],
                'title'  => $lote['title'],
                'pin' => $lote['pin'],
                'description' => $lote['description'],
                'link' => $lote['link'],
                'x' => $lote['position_x'],
                'y' => $lote['position_y'],
                'fill' => $lote['fill'],
                'category' => $lote['category'],
                'action' => $lote['action']
            );
        }
    }
    else
        $results['error'] = lang('core error no_results');

    $results['maxscale'] = '1.8';

    // display results using the JSON formatter helper
    display_json($results);

有什么建议吗?感谢

1 个答案:

答案 0 :(得分:0)

您需要将关卡设为多维数组。

$results['levels'] = array();
$results['levels'][0] = array(
    'id'   => 'lots',
    'title'  => 'Lots',
    'map' => 'maps/lot-map.svg',
    'minimap' => ''
); 

然后当你追加时,按照以下步骤进行:

$results['levels'][0]['locations'][] = array(