可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to process a MySQL select result. My problem is that the sample code below only returns an Array containing all values as string-type even for columns that contain integers and floats.
$sth = mysql_query($selectstr); $rows = array(); while($r = mysql_fetch_row($sth)) { foreach ($r as $value) echo gettype($value), "\n"; }
If I pass that array in $r
to json_encode(..)
I get JavaScript string values in the output (surrounded by quotes) and not unquoted number values (what i need).
How can I query the MySQL database and get a row-array containing the values with the correct type?
Update: Second parameter of mysql_fetch_row(..)
removed. Originally I used mysql_fetch_array(..)
which accepts the second parameter.
回答1:
None of the mysql_fetch_*
functions are supposed to cast values according to their columns' types. For some, PHP doesn't even provide a matching internal data representation (think: BIGINT
).
If you know the data-type of a query's result, you'll need to cast them manually. Otherwise mysql_field_type()
would give you a hint on what type to convert the results to.
回答2:
I suggest folow code:
<?php $sth = mysql_query($selectstr); $rows = array(); while($r = mysql_fetch_row($sth,MYSQL_NUM)) { foreach ($r as $key => $value) { if (is_numeric($value)) { $r[$key] = (float)$value; } } } ?>
回答3:
In the end I changed my code as follows:
$sth = mysql_query($selectstr); $rows = array(); while($r = mysql_fetch_row($sth)) { for ($i = 0; $i < count($r) ; $i++) settype($r[$i],float); }
It assumes that all selected columns in the result set contain numeric values.