PHP Array to Json Object

后端 未结 6 1098
鱼传尺愫
鱼传尺愫 2020-12-09 10:28

I need to convert a PHP array to json but I don\'t get what I expect. I want it to be an object that i can navigate easily with numeric index. Here\'s an example code:

6条回答
  •  遥遥无期
    2020-12-09 11:06

    You want to json_encode($json, JSON_FORCE_OBJECT).

    The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.

    You can also eliminate the use of array_push for some slightly cleaner code:

    $json[] = ['ip' => $ip, 'port' => $port];
    

提交回复
热议问题