如何强制 PHP 使用字符串作为数组键? [英] How can I force PHP to use strings for array keys?

查看:27
本文介绍了如何强制 PHP 使用字符串作为数组键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过一个旧的应用程序,它使用一个 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.

如果我向每个索引添加一个 avar_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"
}

这样我就可以轻松地对它们重新排序,而无需接触更多代码.

This would let me easily reorder them, without having to touch more code.

不起作用.

$newArray = array();
foreach($array as $key => $value) {
   $newArray[(string) $key] = $value;
}

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?

推荐答案

编辑:

我假设如果它们是整数,我不能在不改变的情况下对它们重新排序关键(这在这方面很重要例子).然而,如果他们是字符串,我可以对它们重新排序就像索引不应该一样解释为有任何特殊意义.无论如何,请参阅我的问题更新我是如何做到的(我失败了不同的路线).

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');

如果您手动分配它们,则完全有效.尽管我同意整数键可能会被某人误解为具有顺序含义,尽管您会认为如果它们按非数字顺序排列,很明显它们不是.也就是说,我认为因为您在更新时有更改代码的余地,这是更好的方法.

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('strval', $keys);

$data = array_combine($stringKeys, $values);

//sort your data

这篇关于如何强制 PHP 使用字符串作为数组键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆