我怎么能强制PHP使用字符串数组钥匙? [英] How can I force PHP to use strings for array keys?
问题描述
我遇到一个使用一个ID名称类型的数组,例如旧的应用程序...
I've come across an old app that uses an id to name type array, for example...
array(1) {
[280]=>
string(3) "abc"
}
现在,我需要重新排列这些和的var_dump()
将使其显示这是不会发生的,而钥匙是整数。
Now I need to reorder these, and a var_dump()
would make it appear that that isn't going to happen while the keys are integers.
如果我增加一个 A
来各项指标,的var_dump()
将呈现围绕重点双引号,我想表明它现在是一个字符串...
If I add an a
to every index, var_dump()
will show double quotes around the key, my guess to show it is now a string...
array(1) {
["280a"]=>
string(3) "abc"
}
这将让我轻松地重新排序,而无需接触更多code。
This would let me easily reorder them, without having to touch more code.
这确实无法正常工作
$newArray = array();
foreach($array as $key => $value) {
$newArray[(string) $key] = $value;
}
A 的var_dump()
仍显示他们作为整数数组索引。
A var_dump()
still shows them as integer array indexes.
有没有办法来强制键是字符串,这样我就可以重新排序,不会损坏阵列?
Is there a way to force the keys to be strings, so I can reorder them without ruining the array?
推荐答案
修改
我认为,如果他们是整数,我
在不改变不能重新排序
键(这是显著在此
例)。然而,如果它们是
串,我可以重新排列它们如何
等作为指标不应
除preTED有任何特殊
含义。不管怎样,看到我的问题
更新我做到了(我去了一个
不同的路线)。
I assumed that if they are integers, I can't reorder them without changing the key (which is significant in this example). However, if they were strings, I can reorder them how they like as the index shouldn't be interpreted to have any special meaning. Anyway, see my question update for how I did it (I went down a different route).
其实他们没有要在数字顺序...
Actually they dont have to be in numeric order...
array(208=>'a', 0=> 'b', 99=>'c');
是完全有效的,如果您选择手动分配它们。虽然我同意整数键可能是因为PTED有人有一个连续的意义,尽管如果他们在一个非数字的顺序将是显而易见的,他们的werent你会觉得misinter $ P $。这就是说我想既然你有余地来改变code,你更新的是更好的方法。
Is perfectly valid if youre assigning them manually. Though i agree the integer keys might be misinterpreted as having a sequential meaning by someone although you would think if they were in a non-numeric order it would be evident they werent. That said i think since you had the leeway to change the code as you updated that is the better approach.
也许不是最有效的方式,但易如反掌:
Probably not the most efficient way but easy as pie:
$keys = array_keys($data);
$values = array_values($data);
$stringKeys = array_map($keys, 'strval');
$data = array_combine($stringKeys, $values);
//sort your data
这篇关于我怎么能强制PHP使用字符串数组钥匙?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!