19

I have an array which prints like this

Array ( [0] => 1691864 [1] => 7944458 [2] => 9274078 [3] => 1062072 [4] => 8625335 [5] => 8255371 [6] => 5476104 [7] => 6145446 [8] => 7525604 [9] => 5947143 )

If I json_encode($thearray) I get something like this

[1691864,7944458,9274078,1062072,8625335,8255371,5476104,6145446,7525604,5947143]

Why the name is not encoded (e.g 0, 1 , 2 , 3 etc) ? and how should I do to make it appear in the json code? the full code is below

  $ie = 0;
  while($ie   10)
  {
    $genid = rand(1000000,9999999);
     $temp[$ie] = $genid ;
     $ie++;
     }
     print_r($temp);

    $temp_json = json_encode($temp);
    print_r($temp_json);

4 Answers 4

62

You can force that json_encode uses an object although you’re passing an array with numeric keys by setting the JSON_FORCE_OBJECT option:

json_encode($thearray, JSON_FORCE_OBJECT)

Then the returned value will be a JSON object with numeric keys:

{"0":1691864,"1":7944458,"2":9274078,"3":1062072,"4":8625335,"5":8255371,"6":5476104,"7":6145446,"8":7525604,"9":5947143}

But you should only do this if an object is really required.

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

1 Comment

Didn't know about JSON_FORCE_OBJECT, any downfall using this parameter? Voted ~ Ty
12

Use this instead:

json_encode((object)$temp)

This converts the array into object, which when JSON-encoded, will display the keys.

If you are storing a sequence of data, not a mapping from number to another number, you really should use array.

1 Comment

Note that type juggling like this, especially with array to object, can have some unexpected outcomes. Use with caution.
0

Because those are just the indices of the array. If you want to add some kind of name to each element then you need to use an associative array.

When you decode that JSON array though it will come back out to 0, 1, 2, 3 etc.

Comments

0

This is defined behaviour. The array you show is a non-associative, normally indexed array. Its indexes are implicitly numeric.

If you decode the array in PHP or JavaScript, you will be able to access the elements using the index:

$temp_array = json_decode($temp_json);

echo $temp_array[2]; // 9274078

Comments

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.