PHP Array to Json Object
just use only
$response=array();
$response["0"]=array("ip" => "192.168.0.1",
"port" => "2016");
$json=json_encode($response,JSON_FORCE_OBJECT);
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];
To get array with objects you can create stdClass() instead of array for inner items like below;
<?PHP
$json = array();
$itemObject = new stdClass();
$itemObject->ip = "192.168.0.1";
$itemObject->port = 2016;
array_push($json, $itemObject);
$json = json_encode($json, JSON_PRETTY_PRINT);
echo $json;
?>
A working example http://ideone.com/1QUOm6