0

I can't get my json_encode format that I need.

Current Format:

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

What I need:

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

My current php code:

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

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

I have tried a few things but just can't figure it out.

3
  • A valid JSON data representation won't duplicate keys in the same nesting level. Commented Oct 16, 2013 at 8:38
  • 1
    The JSON array you want is invalid, as it contains duplicate property names in the same object. You probably actually need to include an additional nested array to hold each set of type and item data. Commented Oct 16, 2013 at 8:41
  • 1
    Use jsonlint.com to check with the second json result. Commented Oct 16, 2013 at 8:43

2 Answers 2

2

You could try something like this

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);
Sign up to request clarification or add additional context in comments.

Comments

1

What you actually want is this:

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

which is the output you'll get from Louis H.'s answer's code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.