user3192948
user3192948

Reputation: 251

json_encode method in PHP

Hi I recently came across an example of json_encode function. Very confused about 1 part:

<?php 

$runners=array{

'fname'=>5
'you' => 6
};

echo json_encode (array("runners"=>$runners));

?>

Question is, why can't the code on the last row simply be:

echo json_encode ($runners);

Thanks,

Upvotes: 0

Views: 162

Answers (3)

Amal Murali
Amal Murali

Reputation: 76646

First of all, your array declaration is incorrect and you will get a syntax error if you run the code. You should use array(...) not array{...}. And the values need to be comma-separated. For example:

array(
    key  => value,
    key2 => value2,
    key3 => value3,
    ...
)

The following should work:

$runners = array(
    'fname' => 5,
    'you'   => 6
);

echo json_encode($runners);

Output:

{"fname":5,"you":6}

How are these two different

The end result is different for both cases. When you do json_encode(array("runners"=>$runners));, the array is multi-dimensional, and the JSON output will change, too:

{"runners":{"fname":5,"you":6}}

Which one should you use

Depends. In the first array, you are simply creating two keys named fname and you, and in the second, you also add another key, runners, thereby making the array multi-dimensional. If you want that information to be present in the resulting JSON string, you should use the second one. If not, use the first one.

Upvotes: 4

Awlad Liton
Awlad Liton

Reputation: 9351

First you have use { in array it is not correct. and you have not have , between array elements.
you can use both. but you have to access 2 json by different ways. depending in your choice.

for first (it should be best choice) echo json_encode ($runners); you have one dimensional array.

 $runners=array(

    'fname'=>5,
    'you' => 6
    );
    echo json_encode ($runners);

OUTPUT:

{"fname":5,"you":6}

In second you have 2d array.

     $runners=array(

    'fname'=>5,
    'you' => 6
    );


  echo json_encode (array("runners"=>$runners));

OUTPUT:

{"runners":{"fname":5,"you":6}}

Live Demo : https://eval.in/92104

Upvotes: 1

user2936213
user2936213

Reputation: 1011

Firstly your array is wrogly used. It will use small brackets () not curly {}. So your array will become :

$runners=array(
  'fname' => 5,
  'you'   => 6
);

Now when you do json_encode() as: echo json_encode ($runners); you will get the output:

{"fname":5,"you":6}

And if you do : echo json_encode (array("runners"=>$runners)); you will get output:

{"runners":{"fname":5,"you":6}}

Upvotes: 0

Related Questions