Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I `json_encode()` keys from PHP array?

Tags:

json

arrays

php

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);
like image 685
Michael Avatar asked Jan 30 '11 17:01

Michael


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

How can I get JSON encoded data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

What does json_encode return?

The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.

How check JSON array is empty or not in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.


2 Answers

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.

like image 72
Gumbo Avatar answered Sep 22 '22 06:09

Gumbo


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.

like image 24
Thai Avatar answered Sep 21 '22 06:09

Thai