如何从 PHP 数组中`json_encode()` 键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4844223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I `json_encode()` keys from PHP array?
提问by Michael
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
如果我json_encode($thearray)
得到这样的东西
[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
为什么名称未编码(例如 0、1、2、3 等)?我该怎么做才能让它出现在 json 代码中?完整代码如下
$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);
回答by Gumbo
You can force that json_encode
uses an object although you're passing an array with numeric keys by setting the JSON_FORCE_OBJECToption:
json_encode
尽管您通过设置JSON_FORCE_OBJECT选项传递带有数字键的数组,但您可以强制使用对象:
json_encode($thearray, JSON_FORCE_OBJECT)
Then the returned value will be a JSON object with numeric keys:
然后返回的值将是一个带有数字键的 JSON 对象:
{"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.
但是只有在真正需要一个对象时才应该这样做。
回答by Thai
Use this instead:
改用这个:
json_encode((object)$temp)
This converts the array into object, which when JSON-encoded, will display the keys.
这会将数组转换为对象,当 JSON 编码时,将显示键。
If you are storing a sequence of data, not a mapping from number to another number, you really should use array.
如果您要存储数据序列,而不是从数字到另一个数字的映射,那么您确实应该使用数组。
回答by christophmccann
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.
当您解码该 JSON 数组时,它会返回 0、1、2、3 等。
回答by Pekka
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:
如果您使用 PHP 或 JavaScript 解码数组,您将能够使用索引访问元素:
$temp_array = json_decode($temp_json);
echo $temp_array[2]; // 9274078