Search code examples
phpjsonjson-ld

How to hide the numeric array keys in generated JSON-LD?


I am trying to add JSON-LD to my website. I have the JSON array. But it is invalid because of the array keys.

I am appending the array data as follow:

$data[] = $extra_array_data;

I would assume that would not get me the array key 0,1,2,3,4 etc. But it does when converting it to JSON.

{
    "@context": "https://schema.org",
    "@graph": {
        "0": {
            "@type": [
                "WebPage"
            ],
            "@id": "https://example.com/#website",
            "url": "https://example.com/",
            "name": "example.com",
            "description": null,
            "inLanguage": "nl"
        },
        "@type": [
            "WebPage"
        ],
        "@id": "https://example.com/#webpage",
        "url": "https://example.com/contact",
        "name": null,
        "isPartOf": {
            "@id": "https://example.com#website"
        },
        "datePublished": "2023-03-13T21:29:43.3600Z",
        "dateModified": "2023-03-13T21:29:43.3600Z",
        "description": "",
        "inLanguage": "nl-NL",
        "potentialAction": {
            "@type": "ReadAction",
            "target": [
                "https://example.com/contact"
            ]
        }
    }
}

I hope one can tell me what mistake I am making.

$json_data      = json_encode($return_data, JSON_UNESCAPED_UNICODE);

Solution

  • If you want your $extra_array_data to replace existing keys, than you need to merge arrays:

    $data = array_merge($data, $extra_array_data);
    
    {
        "@context": "https://schema.org",
        "@graph": {
            "@type": [
                "WebPage"
            ],
            "@id": "https://example.com/#website",
            "url": "https://example.com/",
            "name": "example.com",
            "isPartOf": {
                "@id": "https://example.com#website"
            },
            "datePublished": "2023-03-13T21:29:43.3600Z",
            "dateModified": "2023-03-13T21:29:43.3600Z",
            "description": null,
            "inLanguage": "nl",
            "potentialAction": {
                "@type": "ReadAction",
                "target": [
                    "https://example.com/contact"
                ]
            }
        }
    }