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

How to convert empty array to object in php

青灯夜游
Release: 2023-03-12 17:10:02
Original
2414 people have browsed it

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);
Copy after login

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);
Copy after login

Output:

{
  "jsonArray": {
    "0": "21",
    "1": "12",
    "2": "13"
  },
  "jsonObject": {
    
  }
}
Copy after login

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));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template