Home  >  Article  >  Backend Development  >  How to convert php array into json string

How to convert php array into json string

青灯夜游
青灯夜游Original
2021-02-26 14:46:213352browse

In PHP, you can use the json_encode() function to convert an array into a json string, with the syntax "json_encode(array)". The json_encode() function can JSON encode variables and convert arrays into data in json string format.

How to convert php array into json string

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

Convert php array to json string

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
$arr=[&#39;a&#39;=>10,&#39;b&#39;=>100,&#39;c&#39;=>&#39;Hello&#39;];
$str=json_encode($arr); //将数组转json格式的数据
var_dump($arr); 
var_dump($str); 
?>

Output:

How to convert php array into json string

[Recommended learning: "PHP Video Tutorial"]

Description:

json_encode() is used to JSON encode variables, and can convert the data format of objects and arrays into json string format data.

Syntax:

json_encode ( $value [, $options = 0 ] )

Note:

1. $value is the value to be encoded, and this function is only valid for UTF8 encoded data;

2. options: a binary mask composed of the following constants: JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT;

3. The second parameter is generally not needed;

4. JSON data is actually a string. You can use var_dump() to print it out to see the data type.

Return value: If the execution is successful, JSON data is returned, otherwise FALSE is returned.

For more programming related knowledge, please visit: Programming Video! !

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