Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uicabpatweyler's avatar

PHP fix structure for JSON

What would be the structure of this array in PHP to get a JSON string in the following format


"{"message":"message content",
 
errors":
        {
            "attribute_a":["The message content a"],
            "attribute_b":["The message content b"],
            "attribute_c":["The message content c"],
            "attribute_d":["The message content d"]
        }

}"

0 likes
1 reply
lostdreamer_nl's avatar

This should do:

$data = [
    'message' => 'message content',
    'errors' => [
        'attribute_a' => ['The message content a'],
        'attribute_b' => ['The message content b'],
        'attribute_c' => ['The message content c'],
        'attribute_d' => ['The message content d', 'The second message content d'],
    ]
];

echo json_encode($data, JSON_PRETTY_PRINT);
/*
// output:
{
    "message": "message content",
    "errors": {
        "attribute_a": [
            "The message content a"
        ],
        "attribute_b": [
            "The message content b"
        ],
        "attribute_c": [
            "The message content c"
        ],
        "attribute_d": [
            "The message content d",
            "The second message content d"
        ]
    }
}

*/

Simply remember, JSON / JS does not have associative arrays, so if you json encode an associative array in PHP, it will become a JS object.

Please or to participate in this conversation.