mysql中json对象类型转换,使用正确的类型将mysql结果转换为json

I know how to get a mysql-row and convert it to json:

$row = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM table WHERE id=1"));

echo json_encode($row); // it's an ajax-call

but:

the db-row has different types like int, float, string.

by converting it using json_encode() all results are strings.

Is there a better way to correct the types than this:

$row['floatvalue1'] = 0+$row['floatvalue1'];

$row['floatvalue2'] = 0+$row['floatvalue2'];

$row['intvalue1'] = 0+$row['intvalue1'];

I would like to loop through the keys and add 0 because:

first coding rule: DRY - dont repeat yourself

but i can't because:

row has also other types than numbers (string, date)

there are many columns

design is in dev, so columns-names often changes

Thanks in advance and excuse my bad english :-)

EDIT (to answer the comment-question from Casimir et Hippolyte):

I call this php-code using ajax to get dynamically sql-values. in my javascript-code i use the results like this:

result['intvalue1'] += 100;

lets say the json-result of intval1 is 50, the calculated result is:

"50100", not 150

解决方案

The code below is just a proof of concept. It needs encapsulation in a function/method and some polishing before using it in production (f.e. call mysqli_fetch_field() in a loop and store the objects it returns before processing any row, not once for every row).

It uses the function mysqli_fetch_field() to get information about each column of the result set and converts to numbers those columns that have numeric types. The values of MYSQLI_TYPE_* constants can be found in the documentation page of Mysqli predefined constants.

// Get the data

$result = mysqli_query($db, "SELECT * FROM table WHERE id=1");

$row = mysqli_fetch_assoc($result);

// Fix the types

$fixed = array();

foreach ($row as $key => $value) {

$info = mysqli_fetch_field($result);

if (in_array($info->type, array(

MYSQLI_TYPE_TINY, MYSQLI_TYPE_SHORT, MYSQLI_TYPE_INT24,

MYSQLI_TYPE_LONG, MYSQLI_TYPE_LONGLONG,

MYSQLI_TYPE_DECIMAL,

MYSQLI_TYPE_FLOAT, MYSQLI_TYPE_DOUBLE

))) {

$fixed[$key] = 0 + $value;

} else {

$fixed[$key] = $value;

}

}

// Compare the results

echo('all strings: '.json_encode($row)."\n");

echo('fixed types: '.json_encode($fixed)."\n");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值