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.

0

1 Answer 1

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()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.