Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array to Json Object

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 a numeric index. Here's an example code:

$json = array();
$ip = "192.168.0.1";
$port = "2016";
array_push($json, ["ip" => $ip, "port" => $port]);
$json = json_encode($json, JSON_PRETTY_PRINT);
// ----- json_decode($json)["ip"] should be "192.168.0.1" ----
echo $json;

This is what I get

[  
   [  
      "ip" => "192.168.0.1",
      "port" => "2016"
   ]
]

But I want to get an object instead of array:

{  
   "0": {  
      "ip": "192.168.0.1",
      "port": "2016"
   }
}
like image 666
Hassan Ila Avatar asked Jan 30 '16 08:01

Hassan Ila


4 Answers

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];
like image 72
jbafford Avatar answered Oct 08 '22 08:10

jbafford


just use only

$response=array();
$response["0"]=array("ip"     => "192.168.0.1",
                     "port"   => "2016");
$json=json_encode($response,JSON_FORCE_OBJECT);
like image 23
Veshraj Joshi Avatar answered Oct 08 '22 06:10

Veshraj Joshi


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

like image 4
Cihan Uygun Avatar answered Oct 08 '22 08:10

Cihan Uygun


Just in case if you want to access your objectivitized json whole data OR a specific key value:

PHP SIDE

 $json = json_encode($yourdata, JSON_FORCE_OBJECT);

JS SIDE

 var json = <?=$json?>;
 console.log(json);            // {ip:"192.168.0.1", port:"2016"}
 console.log(json['ip']);      // 192.168.0.1
 console.log(json['port']);    // 2016
like image 4
MR_AMDEV Avatar answered Oct 08 '22 08:10

MR_AMDEV