将 JSON 数组中的字符串元素解析为整数
parse string element in JSON array to integer
$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);
我的查询没有问题,但是返回值是..
[{"label":"rrp","data":"5"},{"label":"t","data":"34"},{"label":"tt","data":"4"},{"label":"nutrachin","data":"45"}]
我需要如下所示的 json 数组..
[{"label":"rrp","data":5},{"label":"t","data":34},{"label":"tt","data":4},{"label":"nutrachin","data":45}]
在此数组中数据被视为字符串,我需要将其解析为整数..在此先感谢。
很简单。
while ($r = mysql_fetch_assoc($sth)) {
$r["data"] = intval($r["data"]);
$rows[] = $r;
}
理想情况下,如果 factor
是数字类型,您的数据库连接器将允许您指定要在行中返回的数据类型。例如,PDO and mysqlnd can return native types (see How to get numeric types from MySQL using PDO?)。
但是,您可以执行以下操作:
while ($r = mysql_fetch_assoc($sth)) {
$r['data'] = intval($r['data']);
$rows[] = $r;
}
这样,您的 JSON 编码就会有一个整数。
$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);
我的查询没有问题,但是返回值是..
[{"label":"rrp","data":"5"},{"label":"t","data":"34"},{"label":"tt","data":"4"},{"label":"nutrachin","data":"45"}]
我需要如下所示的 json 数组..
[{"label":"rrp","data":5},{"label":"t","data":34},{"label":"tt","data":4},{"label":"nutrachin","data":45}]
在此数组中数据被视为字符串,我需要将其解析为整数..在此先感谢。
很简单。
while ($r = mysql_fetch_assoc($sth)) {
$r["data"] = intval($r["data"]);
$rows[] = $r;
}
理想情况下,如果 factor
是数字类型,您的数据库连接器将允许您指定要在行中返回的数据类型。例如,PDO and mysqlnd can return native types (see How to get numeric types from MySQL using PDO?)。
但是,您可以执行以下操作:
while ($r = mysql_fetch_assoc($sth)) {
$r['data'] = intval($r['data']);
$rows[] = $r;
}
这样,您的 JSON 编码就会有一个整数。