Home >Backend Development >PHP Problem >How to convert multiple php arrays into one json data
Conversion method: 1. Use the "array_merge_recursive(array 1, array 2, array 3...)" statement to merge multiple arrays into one array; 2. Use json_encode() to convert the merged array For json data, the syntax is "json_encode (merged array)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Convert multiple php Method of converting an array into a json data
1. Use the array_merge_recursive() function to merge multiple arrays into one array
array_merge_recursive(array1,array2,array3...)
Return value : Returns the merged array.
<?php header("Content-type:text/html;charset=utf-8"); $arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); $arr2 = array ('f'=>6,'g'=>7,'h'=>8,'i'=>9,'j'=>10); var_dump($arr1); var_dump($arr2); $arr = array_merge_recursive($arr1,$arr2); var_dump($arr); ?>
2. Use json_encode() function to convert the merged array into json data
json_encode() function can The variable is JSON encoded and a JSON string is returned.
<?php header("Content-type:text/html;charset=utf-8"); $arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); $arr2 = array ('f'=>6,'g'=>7,'h'=>8,'i'=>9,'j'=>10); $arr = array_merge_recursive($arr1,$arr2); var_dump($arr); echo json_encode($arr); ?>
Description:
array_merge_recursive() The function is used to merge one or more arrays into one array.
The difference between this function and the array_merge() function is that it handles the situation where two or more array elements have the same key name. array_merge_recursive() does not perform key name overwriting, but recursively combines multiple values with the same key name into an array.
json_encode() function can JSON encode variables; if successful, a JSON-encoded string will be returned; if failed, false will be returned.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert multiple php arrays into one json data. For more information, please follow other related articles on the PHP Chinese website!