How to merge two PHP JSON array into one

Published May 20, 2017

There will be a time you will find yourself working on two separate PHP JSON (JavaScript Object Notation) array, and will like to merge them together for some certain purposes.

In this tutorial I will be explaining how to merge two PHP JSON array together.

First JSON array

$array1 = '{ "id" : "1", "username" : "James", "access_level" : "1" }';

$array1 = '{

"id" : "1",

"username" : "James",

"access_level" : "1"

}';

//Second JSON array

$array2 = '{ "id" : "2", "username" : "Micheal", "access_level" : "2" }';

$array2 = '{

"id" : "2",

"username" : "Micheal",

"access_level" : "2"

}';

// Declare a PHP array variable.

$users = array();

// json_decode() is used to decode JSON objects and converts it into a Php Variable

// We are using second parameter (true) which is optional

// so as to convert it to array and not object

users[]=json_decode(users[] = json\_decode(array1, true);

users[]=json_decode(users[] = json\_decode(array2, true);

You can take time to read more on json_decode()

We will use json_encode function to convert the PHP array ( $users ) into JSON value

// store the result into merge_user variable $merge_user = json_encode( $users );

// store the result into merge_user variable

$merge_user = json_encode( $users );

And that is all.

// To see the output print_r( $merge_user );

// To see the output

print_r( $merge_user );

// Output

[{"id":"1","username":"James","access_level":"1"},{"id":"2","username":"Micheal","access_level":"2"}]

|

Discover and read more posts from Sokoya Philip
get started
Enjoy this post?

Leave a like and comment for Sokoya