1

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,407
  • 2
  • 21
  • 44
Gunjan Patel
  • 2,220
  • 4
  • 22
  • 43

4 Answers4

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

use the values only.

RST
  • 3,798
  • 2
  • 19
  • 32
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,272
  • 1
  • 9
  • 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,094
  • 26
  • 25