Home > Backend Development > PHP Tutorial > How to Convert a PHP Array to a JSON Array Using `json_encode()`?

How to Convert a PHP Array to a JSON Array Using `json_encode()`?

Mary-Kate Olsen
Release: 2024-12-04 06:01:12
Original
296 people have browsed it

How to Convert a PHP Array to a JSON Array Using `json_encode()`?

How to Convert a PHP Array into a JSON Array

To create a JSON array from a PHP array, utilize the json_encode() function. This function transforms the PHP array into a JSON representation.

Example:

Consider the following PHP array:

$arr = [
  ["region" => "valore", "price" => "valore2"],
  ["region" => "valore", "price" => "valore2"],
  ["region" => "valore", "price" => "valore2"],
];
Copy after login

To convert this PHP array into a JSON array, use json_encode():

$json = json_encode($arr);
Copy after login

The output $json will be:

[
  {"region":"valore","price":"valore2"},
  {"region":"valore","price":"valore2"},
  {"region":"valore","price":"valore2"}
]
Copy after login

Handling Complex Nested Arrays:

For scenarios involving complex nested arrays, refer to the comment by "andyrusterholz" on the PHP documentation page for json_encode() linked below:

http://www.php.net/manual/en/function.json-encode.php

The above is the detailed content of How to Convert a PHP Array to a JSON Array Using `json_encode()`?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template