我该怎么办`json_en code()`从PHP数组键? [英] How do I `json_encode()` keys from PHP array?

查看:96
本文介绍了我该怎么办`json_en code()`从PHP数组键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有打印一个这样的数组

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

如果我 json_en code($ thearray)我得到这样

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

为什么名称不带codeD(例如0,1,2,3等)?我应该怎么做,使之出现在JSON code?
全code是低于

  $即= 0;
  而($即10)
  {
    $ genid,配置=兰特(1000000,9999999);
     $临时[$即] = $ genid,配置;
     $即++;
     }
     的print_r($ TEMP);    $ temp_json = json_en code($ TEMP);
    的print_r($ temp_json);


解决方案

您可以强制 json_en code 使用,虽然你是通过设置传递用数字键数组的对象的 JSON_FORCE_OBJECT 的选项:

  json_en code($ thearray,JSON_FORCE_OBJECT)

则返回值将与数字键的JSON对象:

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

但你只能这样做,如果确实需要的对象。

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);

解决方案

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.

这篇关于我该怎么办`json_en code()`从PHP数组键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆