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
Mary-Kate OlsenOriginal
2024-12-04 06:01:12297browse

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"],
];

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

$json = json_encode($arr);

The output $json will be:

[
  {"region":"valore","price":"valore2"},
  {"region":"valore","price":"valore2"},
  {"region":"valore","price":"valore2"}
]

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!

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