Home  >  Article  >  Backend Development  >  How to convert multiple php arrays into one json data

How to convert multiple php arrays into one json data

青灯夜游
青灯夜游Original
2022-05-26 16:18:252855browse

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)".

How to convert multiple php arrays into one json data

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 (&#39;a&#39;=>1,&#39;b&#39;=>2,&#39;c&#39;=>3,&#39;d&#39;=>4,&#39;e&#39;=>5);
$arr2 = array (&#39;f&#39;=>6,&#39;g&#39;=>7,&#39;h&#39;=>8,&#39;i&#39;=>9,&#39;j&#39;=>10);
var_dump($arr1);
var_dump($arr2);
$arr = array_merge_recursive($arr1,$arr2);
var_dump($arr);
?>

How to convert multiple php arrays into one json data

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 (&#39;a&#39;=>1,&#39;b&#39;=>2,&#39;c&#39;=>3,&#39;d&#39;=>4,&#39;e&#39;=>5);
$arr2 = array (&#39;f&#39;=>6,&#39;g&#39;=>7,&#39;h&#39;=>8,&#39;i&#39;=>9,&#39;j&#39;=>10);
$arr = array_merge_recursive($arr1,$arr2);
var_dump($arr);
echo json_encode($arr);
?>

How to convert multiple php arrays into one json data

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!

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