Codementor Events

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
post commentsBe the first to share your opinion
mani
5 years ago

Hi Sokoya gud evening, Here i want to display particular timing for related date. using php below is the data [“2019/09/30 20:05:10”, “2019/09/30 20:20:12”, “2019/09/30 20:35:11”, “2019/09/30 20:45:11”, “2019/09/30 20:50:13”, “2019/09/30 21:05:13” ]

Juraj Dobrik
6 years ago

Take your example array, you have 30000 entries in it. How much % of data are indexeS?

Show more replies