在php的foreach循环中更改关联数组的$key [英] Change $key of associative array in a foreach loop in php
问题描述
我有一个这样的数组:
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'
)
失败的想法是:
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);
}
我的智慧以这个结尾.我使用的是 Magento 1.9.0.1 CE,但这与这个问题无关.如果您必须知道,我必须这样做的原因是因为我有一堆对象,我将这些对象作为数组返回以组装到 SOAP 客户端.我使用的 API 要求键以大写字母开头……但是,我不希望将对象变量名的第一个字母大写.傻,我知道,但我们都回答某人,而且某人想要那样.
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.
推荐答案
unset
如果它已经是正确的格式,首先它,否则你将删除你刚刚定义的内容:
unset
it first in case it is already in the proper format, otherwise you will remove what you just defined:
foreach($array as $key => $value)
{
unset($array[$key]);
$array[ucfirst($key)] = $value;
}
这篇关于在php的foreach循环中更改关联数组的$key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!