php 在php的foreach循环中更改关联数组的$key
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25068571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change $key of associative array in a foreach loop in php
提问by brianwalleshauser
I have an array like this:
我有一个这样的数组:
array(
'firstName' => 'Joe',
'lastName' => 'Smith'
)
I need to loop over every element in my array and in the end, the array should look like this:
我需要遍历数组中的每个元素,最后,数组应如下所示:
array(
'FirstName' => 'Joe',
'LastName' => 'Smith'
)
Failed idea was:
失败的想法是:
foreach($array as $key => $value)
{
$key = ucfirst($key);
}
This obviously will not work, because the array is not passed by reference. However, all these attempts also fail:
这显然行不通,因为数组不是通过引用传递的。然而,所有这些尝试也都失败了:
foreach(&$array as $key => $value)
{
$key = ucfirst($key);
}
foreach($array as &$key => $value)
{
$key = ucfirst($key);
}
Pretty much at my wits end with this one. I'm using Magento 1.9.0.1 CE, but that's pretty irrelevant for this problem. If you must know, the reason I have to do this is because I have a bunch of object that's I'm returning as an array to be assembled into a SOAP client. The API I'm using requires the keys to begin with a capital letter...however, I don't wish to capitalize the first letter of my object's variable names. Silly, I know, but we all answer to someone, and that someone wants it that way.
几乎在我的智慧中结束了这一点。我使用的是 Magento 1.9.0.1 CE,但这与这个问题无关。如果您必须知道,我必须这样做的原因是因为我有一堆对象,我将这些对象作为数组返回以组装到 SOAP 客户端。我使用的 API 要求键以大写字母开头……但是,我不希望将对象变量名的第一个字母大写。傻,我知道,但我们都回答某人,有人想要那样。
回答by cmorrissey
foreach($array as $key => $value)
{
$array[ucfirst($key)] = $value;
unset($array[$key]);
}
回答by AbraCadaver
You can't modify the keys in a foreach
, so you would need to create a new one and unset the old one. Here is another way:
您无法修改 a 中的键foreach
,因此您需要创建一个新键并取消设置旧键。这是另一种方式:
$array = array_combine(array_map('ucfirst', array_keys($array)), $array);
- Get the keys using
array_keys
- Apply
ucfirst
to the keys usingarray_map
- Combine the new keys with the values using
array_combine
- 使用获取密钥
array_keys
- 应用
ucfirst
使用的密钥array_map
- 使用组合新键和值
array_combine
回答by Skeets
The answers here are dangerous, in the event that the key isn't changed, the element is actually deletedfrom the array. Also, you could unknowingly overwrite an element that was already there.
这里的答案很危险,如果键没有改变,元素实际上是从数组中删除的。此外,您可能会在不知不觉中覆盖已经存在的元素。
You'll want to do some checks first:
你需要先做一些检查:
foreach($array as $key => $value)
{
$newKey = ucfirst($key);
// does this key already exist in the array?
if(isset($array[$newKey])){
// yes, skip this to avoid overwritting an array element!
continue;
}
// Is the new key different from the old key?
if($key === $newKey){
// no, skip this since the key was already what we wanted.
continue;
}
$array[$newKey] = $value;
unset($array[$key]);
}
Of course, you'll probably want to combine these "if" statements with an "or" if you don't need to handle these situations differently.
当然,如果您不需要以不同方式处理这些情况,您可能希望将这些“if”语句与“or”组合起来。
回答by Marc B
This might work:
这可能有效:
foreach($array as $key => $value) {
$newkey = ucfirst($key);
$array[$newkey] = $value;
unset($array[$key]);
}
but it is very risky to modify an array like this while you're looping on it. You might be better off to store the unsettable keys in another array, then have a separate loop to remove them from the original array.
但是在循环时修改这样的数组是非常危险的。您最好将不可设置的键存储在另一个数组中,然后使用单独的循环将它们从原始数组中删除。
And of course, this doesn't check for possible collisions in the aray, e.g. firstname -> FirstName
, where FirstName already existed elsewhere in the array.
当然,这不会检查firstname -> FirstName
数组中可能的冲突,例如,FirstName 已经存在于数组中的其他地方。
But in the end, it boils down to the fact that you can't "rename" a key. You can create a new one and delete the original, but you can't in-place modify the key, because the key ISthe key to lookup an entry in the aray. changing the key's value necessarily changes what that key is pointing at.
但最终,归结为您无法“重命名”密钥的事实。您可以创建一个新的并删除原始的,但您不能就地修改键,因为键是在数组中查找条目的键。更改键的值必然会更改该键所指向的内容。
回答by Alex
Top of my head...
我的头顶...
foreach($array as $key => $value){
$newKey = ucfirst($key);
$array[$newKey] = $value;
unset($array[$key]);
}
Slightly change your way of thinking. Instead of modifying an existing element, create a new one, and remove the old one.
稍微改变一下你的思维方式。不要修改现有元素,而是创建一个新元素,然后删除旧元素。
回答by Harry Lewis
If you use laravel or have Illuminate\Support
somewhere in your dependencies, here's a chainable way:
如果您使用 laravel 或Illuminate\Support
在您的依赖项中有某个地方,这是一种可链接的方式:
>>> collect($array)
->keys()
->map(function ($key) {
return ucfirst($key);
})
->combine($array);
=> Illuminate\Support\Collection {#1389
all: [
"FirstName" => "Joe",
"LastName" => "Smith",
],
}