在 php 中将某些内容存储为 unsignedtinyint

发布于 2024-11-27 12:41:24 字数 237 浏览 0 评论 0原文

有没有办法在 php 中显式地将我的数字存储为tinyint(1 个字节而不是 4 个字节)。

或者我只能通过将它们 4 x 4 存储在 int 中来强制执行此操作? (使用一些二进制操作)

我通过使用 str_split 中断字符串并通过 unpack( 'C' , .. ) 将这些字节解释为整数来生成这些值。 目前,我将这些值作为单个整数存储在数组中,但如果我能以某种方式将它们存储为tinyints,它可以节省大量空间。

Is there a way to explicitly store my numbers in php as tinyint (1 byte instead of 4).

Or could i only enforce this by storing them 4 by 4 in an int? (using a few binary operations)

I generate these values by breaking a string using str_split and interpretting these bytes as ints via unpack( 'C' , .. ).
Currently i store these values in an array as invdividual integers but it could save alot of space if i could store them somehow as tinyints.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枯叶蝶 2024-12-04 12:41:24

PHP 有两种您可能想要在此处使用的数据类型:整数字符串
PHP 没有任何其他类型可供选择(float 对于整数来说不是一个好的选择,其他类型也不合适)。

int 通常为 32 或 64 位,字符串每个字符 1 个字节。*我建议除非您有很多数字,否则 32 位 int 永远不会出现任何问题。如果您绝对想要安全的space内存**并且您的号码最多有3位数字,您可以将您的号码作为字符串处理。甚至还有 BCMath 扩展,可以让您直接对字符串数字进行操作,而无需来回转换它们。尽管收益可能非常有限,但这是相当麻烦的。

尽管MySQL TINYINT通常用于布尔值,但请注意PHP确实有布尔类型......!


* 每一个字节字符一个字节,即。
** 由于 PHP 脚本通常只是非常临时的,因此您应该只遇到峰值内存使用问题,而不是存储空间问题。获得更多 RAM 可能是比使用类型更有效的解决方案。

PHP has two data types that you may want to use here: integer and string.
PHP doesn't have any other types you could choose from (float wouldn't be a good choice for integers, the other types are not appropriate).

An int is usually 32 or 64 bits, a string is 1 byte per character.* I propose that unless you have a lot of numbers, you won't ever see any problem with 32 bit ints. If you absolutely positively want to safe space memory** and your numbers have a maximum of 3 digits, you could handle your numbers as strings. There's even the BCMath extension that'll let you operate on string numbers directly without needing to cast them back and forth. It's quite a lot of hassle for possibly very limited gain though.

Seeing that a MySQL TINYINT is usually used for boolean values though, please be aware PHP does have a boolean type...!


* One byte per one-byte character, that is.
** Since PHP scripts are usually only very temporary, you should only have problems with peak memory usage, not storage space. Getting more RAM may be the more efficient solution than playing with types.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文