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":{}}
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.
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.
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() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With