Home  >  Article  >  Backend Development  >  How to convert empty array to object in php

How to convert empty array to object in php

青灯夜游
青灯夜游Original
2021-09-17 18:53:112268browse

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)".

How to convert empty array to object in php

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);

How to convert empty array to object in php

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:

How to convert empty array to object in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn