使用PHP生成JSON

时间:2015-04-03 11:23:31

标签: php arrays json

我有2个txt文件,第一个是所有汽车制造商,第二个是汽车制造商的每个型号。我想将make / model变成JSON,它应该是这样的:

[{"value":"ACURA","title":"Acura","models":
    [{"value":"CL_MODELS","title":"CL Models (4)"},
    {"value":"2.2CL","title":" - 2.2CL"},
    {"value":"2.3CL","title":" - 2.3CL"},
    {"value":"MDX","title":"MDX"},
    {"value":"NSX","title":"NSX"},
    {"value":"RDX","title":"RDX"},
    {"value":"ACUOTH","title":"Other Acura Models"}]},
{"value":"ALFA","title":"Alfa Romeo","models":
    [{"value":"ALFA164","title":"164"},
    {"value":"ALFA8C","title":"8C Competizione"},
    {"value":"ALFAGT","title":"GTV-6"},
    {"value":"MIL","title":"Milano"},
    {"value":"SPID","title":"Spider"},
    {"value":"ALFAOTH","title":"Other Alfa Romeo Models"}]}]

即使我必须手动执行此操作,有人可以给我正确的方法吗? 提前谢谢,我真的很感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

该过程如下所示: 1.解析文件中的数据并将其保存到数组中。 2.在数组上使用json_encode()。

如果没有数据格式,您将无法从我们这里获得代码。如何帮助您解析不知道如何的数据:/

答案 1 :(得分:0)

您可以对数组进行编码:

$cars = [
    'ALFA' => [
        'title' => 'Alfa Romeo',
        'models' => [ ... ]
    ],
    'ACURA' => [
        'title' => 'Acura',
        'models' => [ ... ]
    ],
];

然后可以通过json_encode()运行。