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);
The json_encode() function is used to encode a value to JSON format.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With