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

How to convert empty array to json object in php

藏色散人
藏色散人Original
2021-04-02 09:45:223015browse

php method to convert empty array to json object: 1. Use "JSON_FORCE_OBJECT" to convert json object; 2. Use data type conversion to convert empty array to json object; 3. Use ArrayObject to convert empty array to json object.

How to convert empty array to json object in php

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

PHP json_encode converts empty arrays into objects

Problem Description:

php provides interfaces to the client, such as PC, Android, ios, etc. If data in json format is returned, when the returned data is Array, and the key is a string, jsonObject will be returned after jsonization. However, if it is an empty array, jsonArray may be returned. Inconsistency in the data structure causes the end to parse json to fail.

For example:

$arr  = [
     'id'  => 123.,
     'name'  =>  'andrew' ,
];
 
$jsonRet  = json_encode( $arr );
 
print_r( $jsonRet );

Output:

{
  "id": 123,
  "name": "andrew"
}

But if it is:

$arr = [];
$jsonRet = json_encode($arr);
print_r($jsonRet);

Output:

[
  
]

How to when the array is empty Is it also JsonObject?

Method 1:

Use JSON_FORCE_OBJECT

$arr = [];
$jsonRet = json_encode($arr, JSON_FORCE_OBJECT);
print_r($jsonRet);

This method has a drawback, eg:

$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": {
    
  }
}

The original jsonArray has also been jsonObjectified, and local changes cannot affect the global

Method 2

Use data type conversion

$bar = array();  
$foo = (object)$bar;  
echo json_encode($foo);

Method three (recommended)

Use ArrayObject

$arr = [
    'jsonArray' => [
        '21', '12', '13'
    ],
    'jsonObject' => new \ArrayObject()
];
$jsonRet = json_encode($arr);
print_r($jsonRet);

Output:

{
  "jsonArray": [
    "21",
    "12",
    "13"
  ],
  "jsonObject": {
    
  }
}

[Recommended learning: PHP video tutorial]

The above is the detailed content of How to convert empty array to json 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