PHP Realizes Array to JSon and JSon to Array Method Example

  • 2021-10-16 01:13:10
  • OfStack

This paper describes the method of PHP converting array to JSon and JSon converting array. Share it for your reference, as follows:

Array to JSon data:


$array_1 = array(); //1 Dimensional array 
$array_2 = array(); // Multidimensional array 
$array_1['username']='ericwolf';
$array_1['age']=25;
$array_2['menber']['aa']['username']='ericwolf';
$array_2['menber']['aa']['age']=25;
$array_2['menber']['bb']['username']='eeee';
$array_2['menber']['bb']['age']=22;
print_r($array_2);
$jsonObj_1 = json_encode($array_1);
var_dump($jsonObj_1);
$jsonObj_1 = json_encode($array_2);
var_dump($jsonObj_1);

Run results:

Array
(
[menber] = > Array
(
[aa] = > Array
(
[username] = > ericwolf
[age] = > 25
)
[bb] = > Array
(
[username] = > eeee
[age] = > 22
)
)
)
string(32) "{"username":"ericwolf","age":25}"
string(84) "{"menber":{"aa":{"username":"ericwolf","age":25},"bb":{"username":"eeee","age":22}}}"

JSon turns the array and prints:


$jsonStr = '{"key":"value","key1":"value1"}';
$json2Array = json_decode($jsonStr,true);
foreach($json2Array as $key=>$val) {
  echo $key."=".$val."<br/>";
}

Run results:

key=value
key1=value1

PS: Here we recommend several practical json online tools for your reference:

Online JSON code verification, verification, beautification and formatting tools:
http://tools.ofstack.com/code/json

JSON Online Formatting Tool:
http://tools.ofstack.com/code/jsonformat

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

json code online formatting/beautification/compression/editing/conversion tool:
http://tools.ofstack.com/code/jsoncodeformat

C Language Style/HTML/CSS/json Code Formatting and Beautification Tool:
http://tools.ofstack.com/code/ccode_html_css_json

For more readers interested in PHP related contents, please check the topics on this site: "Summary of json Format Data Operation Skills in PHP", "Summary of PHP Mathematical Operation Skills", "Introduction to PHP Basic Grammar", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: