-6

for example `

    $json =
    Array
    (
    [1] => b
    [1] => c
    [1] => d
    ) 

i just want to take the first one [1] => b and ignore the rest

  • Duplicate key not possible in `json` or even in `array` – B. Desai Jul 22 '17 at 05:05
  • keys are always unique. you can't make it duplicate – Ankit Singh Jul 22 '17 at 05:09
  • would you please explain why this required to you ? – Vishal Solanki Jul 22 '17 at 05:10
  • what about this? https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object – Afif Makarim Jul 22 '17 at 05:10
  • Neither in json, nor in array this is possible.Thanks.Check what i am saying:- https://eval.in/836017 – Anant Kumar Singh Jul 22 '17 at 05:20
  • Read that one carefully. _That most implementations of JSON libraries do not accept duplicate keys does not conflict with the standard_ -> **It is expected that other standards will refer to this one, strictly adhering to the JSON text format, while imposing restrictions on various encoding details. Such standards may require specific behaviours. JSON itself specifies no behaviour.** – icecub Jul 22 '17 at 05:22
  • hmm i get it now. thanks for the answer – Afif Makarim Jul 22 '17 at 05:45

1 Answers1

1

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"
user3942918
  • 24,679
  • 11
  • 53
  • 67