在PHP的foreach循环中更改关联数组的$ key [英] Change $key of associative array in a foreach loop in php

查看:758
本文介绍了在PHP的foreach循环中更改关联数组的$ key的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  array(
'firstName'=>'Joe',
'lastName'=>'Smith'

我需要循环遍历数组中的每个元素,最后,数组应该如下所示:
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' FirstName'=>'Joe',
'LastName'=>'Smith'

失败的想法是:

$ foreach($ array为$ key => $ value)
{
$ key = ucfirst($ key);





$ b

这显然是行不通的,因为数组不是通过引用传递的。但是,所有这些尝试也都失败了:
$ b $ $ $ $ $ $ $ $ $ $ foreach(& $ array $ key => $ value)
{
$ key = ucfirst($ key);


$ b foreach($ array as& $ key => $ value)
{
$ key = ucfirst($ key);





$ b

我正在使用Magento 1.9.0.1 CE,但这是相当不相关的这个问题。如果你必须知道,我必须这样做的原因是因为我有一堆对象,我将作为一个数组返回来组装到一个SOAP客户端中。我使用的API要求键以大写字母开头......但是,我不希望大写我的对象的变量名的第一个字母。傻,我知道,但我们都回答某个人,而且有人要这样。

foreach($ array as $ key => $ value)
{
$ array [ucfirst($ key)] = $ value;
unset($ array [$ key]);
}


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.

解决方案

foreach($array as $key => $value)
    {
        $array[ucfirst($key)] = $value;
        unset($array[$key]);
    }

这篇关于在PHP的foreach循环中更改关联数组的$ key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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