2
<?php
    
    $array = Array("1" => 1, "2" =>4);
    $array1 = Array("3" => 5);
    $temp = array_merge($array, $array1);

    echo json_encode($temp);
?>

It gives the following output

[1,4,5]

but, I need the following output

{"1":1,"2":4,"3":5}

Anyone, please answer this.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98

1 Answers1

3

You need to use + instead of array_merge to preserve keys and make json_encode() work properly.

<?php
    
    $array = Array(1 => 1, 2 =>4);
    $array1 = Array(3 => 5);
    $temp = $array  + $array1;
    print_r($temp);
    echo json_encode($temp);

https://3v4l.org/Fdljn

Note: In case still you are getting output like what you shown in your question, then use JSON_FORCE_OBJECT as second parameter to json_encode()

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98