![]() |
Encoding arrays into JSON format is a common task in PHP, especially when building APIs or handling AJAX requests. Below are the approaches to encode arrays into JSON using PHP: Using json_encode()PHP provides a built-in function json_encode() to encode PHP data structures, including arrays, into JSON format. It automatically handles most data types, making it simple and efficient. Example: The example below shows How to encode an array in JSON PHP Using json_encode().
Output {"name":"John","age":30,"city":"New York"} Encoding Associative ArraysAssociative arrays, also known as key-value pairs, are commonly used in PHP. When encoding associative arrays into JSON, the keys become the property names, and the values become the property values in the resulting JSON object. Example: The example below shows How to encode an array in JSON PHP Using Encoding Associative Arrays.
Output {"name":"Jane","age":25,"city":"Los Angeles"} Custom JSON SerializationIn this approach, PHP jsonSerialize() method allows you to implement custom JSON serialization for your objects. In some cases, you may need more control over the JSON output, such as converting objects or complex data structures into JSON. Example: The example below shows How to encode an array in JSON PHP Using Custom JSON Serialization.
Output {"name":"Alice","age":35} |
Reffered: https://www.geeksforgeeks.org
PHP |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |