简体   繁体   中英

Object JSON response using PHP

I am trying to generate a JSON response using PHP that should look like this:

Records={{"country":"United States","fixed":0.20,"cellular":0.35}, {"country":"Canada","fixed":0.30,"cellular":0.45}}

But when I run the code, this is what I get:

Records={"0": {"country":"United States","fixed":0.20,"cellular":0.35}, "1":{"country":"Canada","fixed":0.30,"cellular":0.45}}

This is my PHP code:

$arr_o = array();

array_push($arr_o, array("country" => "United States", "fixed" => 0.20, "cellular" => 0.35));
array_push($arr_o, array("country" => "Canada", "fixed" => 0.30, "cellular" => 0.45));

return json_encode((object)$arr_o);

The array_push method adds the second parameter (your populated "JSON" array) to the existing empty array as an element of that array.

For example:

$a = array();
array_push($a, 1);
print_r($a)

Yields:

Array
(
   [0] => 1
)

If your parameter itself is an array, then it will be appended as an element:

$b = array();
array_push($b, 1);
array_push($b, array(2, 3));
print_r($b);

Yields:

Array
(
    [0] => 1
    [1] => Array
        (
            [0] => 2
            [1] => 3
        )

)

If you want to append the elements of one array on to the end of an existing array, one solution is to use the array_merge method, for example:

$c = array(1);
$c = array_merge($c, array((2, 3, 4));
print_r($c);

Yields:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

See more on array_merge on the following PHP documentation: http://php.net/manual/en/function.array-merge.php

As others have already noted, the "{}" should also be converted to "[]" for the output to be valid JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM