json_encode格式正确

时间:2013-10-16 08:37:15

标签: php json

我无法获得我需要的json_encode格式。

当前格式:

{
    "substantiv": [
        {"text":"auto"},
        {"text":"noch ein auto"}
    ],
    "verben":[
        {"text":"auto fahren"}
    ]
}

我需要什么:

[
    {
        "type":"substantiv",
        "items": [
            {"text":"auto"},
            {"text":"noch ein auto"}
        ]
    } , {
        "type":"verben",
        "items": [
            {"text":"auto fahren"}
        ]
    }
]

我目前的PHP代码:

$data = array();
while($row = $rs->fetch_assoc()){
    $tmp = array(
        "text" => $row['gtext']
        );

    $data[$row['type']][] = $tmp;
}
echo json_encode($data);

我尝试了一些事情但是无法理解。

2 个答案:

答案 0 :(得分:3)

你可以试试这样的事情

while($row = $rs->fetch_assoc()){
    $data[$row['type']][] = array(
        "text" => $row['gtext']
    );
}

$result = array();
foreach($data AS $type => $items) {
    $result[] = array(
        'type' => $type,
        'items' => $items
    );
}

echo json_encode($result);

答案 1 :(得分:2)

你真正想要的是:

[
    {
        "type": "substantiv",
        "items": [
            {
                "text": "auto"
            },
            {
                "text": "noch ein auto"
            }
        ]
    },
    {
        "type": "verben",
        "items": [
            {
                "text": "auto fahren"
            }
        ]
    }
]

这是你从路易斯H.答案的代码中获得的输出。