Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode function not return Braces {} when array is empty in php

Tags:

json

arrays

php

I have this code

$status = array(                 "message"=>"error",                 "club_id"=>$_club_id,                 "status"=>"1",                 "membership_info"=>array(),                 ); 

echo json_encode($status);

This function return json:
{"message":"error","club_id":275,"status":"1","membership_info":[]}

But I need json like this:

{"message":"error","club_id":275,"status":"1","membership_info":{}}

like image 575
Umashankar Saw Avatar asked Jan 28 '15 10:01

Umashankar Saw


People also ask

What does the PHP function json_encode () do?

PHP | json_encode() Function The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation. Parameters: $value: It is a mandatory parameter which defines the value to be encoded.

What is json_encode and Json_decode in PHP?

JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.


1 Answers

use the JSON_FORCE_OBJECT option of json_encode:

json_encode($status, JSON_FORCE_OBJECT); 

Documentation

JSON_FORCE_OBJECT (integer) Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.

Or, if you want to preserve your "other" arrays inside your object, don't use the previous answer, just use this:

$status = array(                 "message"=>"error",                 "club_id"=>$_club_id,                 "status"=>"1",                 "membership_info"=> new stdClass()                 ); 
like image 173
Taha Paksu Avatar answered Sep 21 '22 13:09

Taha Paksu