atc
atc

Reputation: 621

Converting to json correct way using php?

I need an o/p like this ["12","13"] when I do the following json operation

I have a 2 varaiables and getting these values as post data

$a = $_POST['cas'];
$b = $_POST['casty'];

$final1 = json_encode($a);
$final2= json_encode($b);

$final_value = '['.$final1.','.$final2.']';

I am getting output as ["12","13"].I am doing correct way in php ? any other ways to get json object apart from this ?

Upvotes: 1

Views: 51

Answers (1)

vaso123
vaso123

Reputation: 12391

Use an array for that like this:

$array = array($_POST['cas'], $_POST['casty']);
$final_value = json_encode($array);

Note: no need to create $a and $b.

By adding JSON_FORCE_OBJECT as a 2nd parmeter you'll get key => value data like a normal php array. JSON Arrays don't have keys, therefore most of the time JSON_FORCE_OBJECT is useful.

JSON Array ["data", "data2", "data3"] 
JSON Object {0:"data", 1:"data2", 2:"data3"}    

Upvotes: 4

Related Questions