1
 $con = new DBConnector();
 $sth =  $con->Query("SELECT medicinename as label, factor as data FROM medicine_master_tbl limit 4");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
         $rows[] = $r;
      }
echo json_encode($rows);

there is no problem with my query,but the returned value is ..

[{"label":"rrp","data":"5"},{"label":"t","data":"34"},{"label":"tt","data":"4"},{"label":"nutrachin","data":"45"}]

i need the json array as like below..

[{"label":"rrp","data":5},{"label":"t","data":34},{"label":"tt","data":4},{"label":"nutrachin","data":45}]

which the data is considered as string in this array , i need to be parse it as integer .. thanks in advance.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
Sarath
  • 2,318
  • 1
  • 12
  • 24

2 Answers2

2

An easy one.

while ($r = mysql_fetch_assoc($sth)) {
     $r["data"] = intval($r["data"]);
     $rows[] = $r;
}
Saren Arterius
  • 1,330
  • 1
  • 11
  • 15
1

Ideally your database connector would allow you to specify what type of data you are returning in the row, if factor is a numeric type. For instance, PDO and mysqlnd can return native types (see How to get numeric types from MySQL using PDO?).

However, you can do the following:

while ($r = mysql_fetch_assoc($sth)) {
    $r['data'] = intval($r['data']);
    $rows[] = $r;
}

This way, your JSON encoding will have an integer.

Community
  • 1
  • 1
cmbuckley
  • 40,217
  • 9
  • 77
  • 91