-4

I have two Two Dimensional json.

[{"4":"213231.jpg"},{"5":"Cadbury 5 star Chocolate.jpg"}]

[{"1":"slider-1.png"},{"2":"slider-2.png"},{"3":"slider-3.png"},{"4":"slider-4.png"},{"5":"slider-5.png"}]

i want to merge this two arrays and i want the answer as

[{"1":"slider-1.png"},{"2":"slider-2.png"},{"3":"slider-3.png"},{"4":"213231.jpg"},{"5":"Cadbury 5 star Chocolate.jpg"}]
Kavin Smk
  • 808
  • 11
  • 37
  • What is the problem and what does your first array look like exactly? – jeroen Jun 19 '15 at 11:04
  • i dont know how to merge it? – Kavin Smk Jun 19 '15 at 11:05
  • 1
    You are not merging anything, your output is the same as your second array of your input. – jeroen Jun 19 '15 at 11:06
  • now i correct it please take a look.. – Kavin Smk Jun 19 '15 at 11:08
  • Refer this link might help you : http://stackoverflow.com/questions/20286208/merging-two-json-in-php – Durga Jun 19 '15 at 11:27
  • In both json ,You have "5",which "5" you want in merged json ,don't you want both values of it? because in your merged json you took first value ,Is that only value you want? – Durga Jun 19 '15 at 11:36
  • yes that only i want.. – Kavin Smk Jun 19 '15 at 12:01
  • There is no such thing as merging `JSON`s. `JSON` is just an encoding of some data structure. Use `json_decode('...', TRUE)` to restore the data as arrays and use of (or more) of the many PHP [array functions](http://php.net/manual/en/ref.array.php) to get the data structure you want. Also, if you display the decoded data structures (using `print_r()` or `var_export()`) everything becomes more clear. – axiac Jun 19 '15 at 12:27

2 Answers2

1

Try following:

$json1 = '[{"1":"slider-1.png"},{"2":"slider-2.png"},{"3":"slider-3.png"},{"4":"slider-4.png"},{"5":"slider-5.png"}]';
$json2 = '[{"4":"213231.jpg"},{"5":"Cadbury 5 star Chocolate.jpg"}]';

echo json_encode(array_merge(json_decode($json1), json_decode($json2)));

Output

[{"1":"slider-1.png"},{"2":"slider-2.png"},{"3":"slider-3.png"},{"4":"slider-4.png"},{"5":"slider-5.png"},{"4":"213231.jpg"},{"5":"Cadbury 5 star Chocolate.jpg"}]

Bora
  • 10,529
  • 5
  • 43
  • 73
0

Try this :

$json1 = '[{"1":"slider-1.png"},{"2":"slider-2.png"},{"3":"slider-3.png"},{"4":"slider-4.png"},{"5":"slider-5.png"}]';
$json2 = '[{"4":"213231.jpg"},{"5":"Cadbury 5 star Chocolate.jpg"}]';

$json1 = json_decode($json1);
unset($json1[4],$json1[5]);
$json1 = json_encode($json1);
echo json_encode(array_merge(json_decode($json1), json_decode($json2)));
Durga
  • 1,283
  • 9
  • 28
  • 54