2

When I print_r($arr) something like Array ( [0] => Hello [1] => world); is output.

I tried to convert in JSON string using below code.

$result['result'] = $arr;
json_encode($result);

This results in this JSON string:

{"result" : { "0" : "hello" , "1" : "world"}}

The expected result would be this:

{ "result" : ["hello" , "world"]}

What can I do to get the desired output?

Lars Ebert
  • 3,487
  • 2
  • 24
  • 46
Gunjan Patel
  • 2,342
  • 4
  • 24
  • 45

4 Answers4

5
$result['result'] = array_values($arr);
json_encode($result);

use the values only.

RST
  • 3,899
  • 2
  • 20
  • 33
2

Its pretty simple, please use code given below.

$arr = array("0"=>'hello',"1"=>'world');
$result['result'] = array_values($arr);
echo json_encode($result);

Thanks Amit

Amit Shah
  • 1,380
  • 1
  • 10
  • 19
0

Need to do like this:

$result['result'] = array_values($arr);
0

put your array values to the result key of array. then it will print the required result.

$arr = array("0"=>'one',"1"=>'two');
$result['result'] = array_values($arr);
echo json_encode($result);

online demo http://sandbox.onlinephpfunctions.com/code/c4227f1bbeb675c6950d9e4e0f189477153dff3e

Muhammad Tahir
  • 2,351
  • 29
  • 25