PHP - 将 int 键转换为字符串?
我前段时间写了一些大型 PHP 函数。它们包含一些关联数组。到目前为止,我对这些数组没有任何问题,因为它们包含 string 和 int 类型的键(如“brown”和 118)。问题是,当键都是 int 时,它们不会被保留,而是被转换为 0、1 等。
有没有办法强制数组保留我给它的键,即使它们都是 int ?这些功能相当大,更改它们需要很长时间。
编辑
正如 Mike B 的直觉,我使用了一个排序函数,它似乎可以重新索引数组。我正在使用在这里找到的函数: 根据另一个数组按键对数组进行排序?
这是第一个,Erin 的那个,但它没有保留正确的索引。我尝试了Boombastic编辑的版本,效果很好。
感谢您的所有回答!
I have a few large PHP functions written some time ago. They contain some associative arrays. Until now, I had no problem with these arrays because they contained keys of type string and int (like "brown" and 118). The problem is, when the keys are all int, they are not kept, instead the are converted to 0, 1 etc.
Is there any way to force an array to keep the keys I give to it, even if they are all int? The functions are pretty large and it would take too long to change them.
EDIT
As Mike B intuited, I use a sorting function which seems to reindex the arrays. I was using a function I found here: Sort an Array by keys based on another Array?
It was the first one, the one of Erin, but it didn't keep the correct indexes. I tried the version edited by Boombastic and it works well.
Thanks for all your answers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对
$array = ['00'=>'x','11'=>'y']
也有类似的问题,它被转换为整数键,丢失了“0”数字。只是为了在 5 年后提供答案...
KennyD 的答案可以简化为,
...但是,正如 MikeB 评论的那样,KennyD 的答案是错误的,正确的是:
或者以(丑陋的)函数式风格,
(没有直接的正如我检查的那样)。
关于通过
var_dump()
或var_export()
检查:解析为数字时将字符串显示为数字(例如,'123'
为123
),但是,它没有丢失字符串(!),例如数组('00'=>'x',11 =>'y',)
。I have similar problem with
$array = ['00'=>'x','11'=>'y']
that was converted to integer keys, losting a '0' digit.Writing only to offer an answer 5 years after...
The KennyDs answer can be simplified by,
... but, as MikeB commented, KennyDs answer is wrong, the correct is:
or in a (ugly) functional style,
(no direct way as I checked).
About check by
var_dump()
orvar_export()
: show string as number when parse as number (eg.'123'
as123
), but, it not lost string (!), the examplearray ( '00' => 'x', 11 => 'y',)
.您也可以只遍历数组并将所有 int 转换为字符串?
编辑:如果您需要键为 int,那么只需确保在填充数组时在 $key 之前添加 (int) 强制转换。
You could also just go over the array and cast all the int's to a string?
Edit: if you need your keys to be int then just make sure when you are filling the array you add an (int) cast before the $key.