Home >Backend Development >PHP Problem >How to convert empty array to object in php
In PHP, you can use the json_encode() function to convert an empty array into an object, with the syntax "json_encode($arr, JSON_FORCE_OBJECT)" or "json_encode($arr,JSON_UNESCAPED_UNICODE)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php will empty array Convert to object
Method 1:Use JSON_FORCE_OBJECT
$arr = []; $jsonRet = json_encode($arr, JSON_FORCE_OBJECT); var_dump($jsonRet);
Disadvantages: All data will become jsonObject
$arr = [ 'jsonArray' => [ '21', '12', '13' ], 'jsonObject' => [] ]; $jsonRet = json_encode($arr,JSON_FORCE_OBJECT); print_r($jsonRet);
Output:
{ "jsonArray": { "0": "21", "1": "12", "2": "13" }, "jsonObject": { } }
You can see The original jsonArray has also been jsonObjectified
Method Two: (Recommended)
Use ArrayObject
$array = new ArrayObject(); var_dump(json_encode($array,JSON_UNESCAPED_UNICODE));
Output:
Recommended learning: "PHP Video Tutorial 》
The above is the detailed content of How to convert empty array to object in php. For more information, please follow other related articles on the PHP Chinese website!