How to get the first key of many duplicated json key? [duplicate]

What you’ve given here is not JSON, and you won’t be able to create an array in PHP that has duplicate keys. While it is valid for duplicate keys to exist on an object’s properties in JSON, it is discouraged as most parsers (including json_decode) will not give you access to all of them.

However streaming parsers usually will let you get at each of these.

An example using one I wrote, pcrov/JsonReader:

use \pcrov\JsonReader\JsonReader;

$json = <<<'JSON'
{
    "foo": "bar",
    "foo": "baz",
    "foo": "quux"
}
JSON;

$reader = new JsonReader();
$reader->json($json);
$reader->read("foo"); // Read to the first property named "foo"
var_dump($reader->value()); // Dump its value
$reader->close(); // Close the reader, ignoring the rest.

Outputs:

string(3) "bar"

Or if you’d like to get each of them:

$reader = new JsonReader();
$reader->json($json);
while ($reader->read("foo")) {
    var_dump($reader->value());
}
$reader->close();

Outputs:

string(3) "bar"
string(3) "baz"
string(4) "quux"

Leave a Comment