如何从 PHP 数组中`json_encode()` 键? [英] How do I `json_encode()` keys from PHP array?
问题描述
我有一个像这样打印的数组
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 )
如果我 json_encode($thearray)
我得到这样的东西
If I json_encode($thearray)
I get something like this
[1691864,7944458,9274078,1062072,8625335,8255371,5476104,6145446,7525604,5947143]
为什么名称未编码(例如 0、1、2、3 等)?我该怎么做才能让它出现在 json 代码中?完整代码如下
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);
推荐答案
你可以强制json_encode
使用一个对象,尽管您通过设置 JSON_FORCE_OBJECT 选项传递一个带有数字键的数组:
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)
那么返回的值将是一个带有数字键的 JSON 对象:
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.
这篇关于如何从 PHP 数组中`json_encode()` 键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!