How to get the first key of many duplicated json key?

This question already has an answer here:

  • Does JSON syntax allow duplicate keys in an object? 11 answers

  • 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 pcrovJsonReaderJsonReader;
    
    $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"
    
    链接地址: http://www.djcxy.com/p/37826.html

    上一篇: 使用C#返回带有重复键的Json对象

    下一篇: 如何获得许多重复的JSON密钥的第一个键?