【问题标题】:PHP String to Int for MySQL Unique IDMySQL 唯一 ID 的 PHP 字符串到 Int
【发布时间】:2016-06-05 13:46:17
【问题描述】:

我想将从我的 MYSQL 数据库中检索为字符串的 17 位唯一 ID 转换为数字。我使用 int 来做到这一点。但是最后我得到一个零:

$num = 96435171263250434;
(int)$num --> 96435171263250430

我检查过我运行的是 64 位系统。我得到以下信息:

php -r 'echo PHP_INT_MAX;'
9223372036854775807

我该如何解决这个问题???

【问题讨论】:

  • 我在这里要说的应该和我想的没什么不同,但是你试过使用intval() 函数吗?它返回一个字符串的整数值。

标签: php


【解决方案1】:

cannot超过PHP_INT_MAX

$num = "96435171263250434";

$x = (float) $num; // This should hold it but it's a float

$maxIntMult = 0;

$maxIntMult = intval($x / PHP_INT_MAX); 

$remainder = $x - $maxIntMult * PHP_INT_MAX;


echo PHP_INT_MAX . " x "  .$maxIntMult. " + " . $remainder; // function of two integer if you can't work with floats and you can make something of this

您可以尝试利用 id 没有负值这一事实,有效地将您的范围加倍。

$num = PHP_INT_MAX + 50;

$x = (float) $num;

$intX = $num - PHP_INT_MAX;

echo $intX; // Shows 50 with the '0' being -PHP_INT_MAX



function getIdWithNonZeroOffset($stringId)
{
   $x = (float) $stringId;

  $intX = $x - PHP_INT_MAX;

   return $intX; 
}

function getStringFromNonZeroOfssetId($id)
{
   return (string) ($id + PHP_INT_MAX);
}

echo getIdWithNonZeroOffset((string)(PHP_INT_MAX + 200)); // Gives 200 (store this in int column)

echo getStringFromNonZeroOfssetId(200); // Gives "2147483847" (my max int is "2147483647")

【讨论】:

  • 谢谢 我假设没有简单的解决方案。因此,我决定将其保留为字符串并像那样工作。感谢上面的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2011-08-09
  • 2011-10-23
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多