2

I have this simple array with 2 elements which is being converted into json format:

echo '['.json_encode(array("name" => "FRENCH POLYNESIA", "name" => "POLAND")).']';

The result is: [{"name":"POLAND"}]

In my case I need this result: [{"name": "FRENCH POLYNESIA"},{"name": "POLAND"}] How I can do this ?

4
  • 1
    You can't create two keys in the same array, the last one will overwrite the previous values. Commented Mar 15, 2018 at 22:23
  • echo json_encode([array("name" => "FRENCH POLYNESIA"), array("name" => "Poland")]); Commented Mar 15, 2018 at 22:24
  • even without json_decode you will not be able to initialize array with key duplicated. so change/fix array initialization up to your needs Commented Mar 15, 2018 at 22:26
  • I mean you can't create two identical* keys. Commented Apr 4, 2018 at 17:26

2 Answers 2

3

This JSON:

[{"name": "FRENCH POLYNESIA"},{"name": "POLAND"}]

is an array containing two objects. So you need your input array to contain two arrays rather than two key-value pairs.

array(array("name" => "FRENCH POLYNESIA"), array("name" => "POLAND"))

json_encode will convert the inner arrays to objects.

It's already been mentioned in the comments, but your original array format doesn't make sense because you can't have two of the same array key anyway.

Sign up to request clarification or add additional context in comments.

Comments

0

You can't create two (or more) identical keys in the same array, the last value will overwrite the previous ones.

This value:

[{"name": "FRENCH POLYNESIA"},{"name": "POLAND"}]

Is decoded to

array (size=2)
  0 => 
    array (size=1)
      'name' => string 'FRENCH POLYNESIA' (length=16)
  1 => 
    array (size=1)
      'name' => string 'POLAND' (length=6)

So to answer your question, your array should look like this

$array = [
    array(
       'name' => 'FRENCH POLYNESIA'
    ),
    array(
       'name' => 'POLAND'
    ),
];

2 Comments

"You can't create two keys in the same array." Missing probably a word, right?
@Syscall Yes, I fixed it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.