在 PHP 中更改关联数组中的键 [英] Change key in associative array in PHP

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

问题描述

假设我有一个这样的数组:

Say I have an array like this:

array(2) {
  [0]=> array(2) {
    ["n"]=> string(4) "john"
    ["l"]=> string(3) "red"
  }
  [1]=> array(2) {
    ["n"]=> string(5) "nicel"
    ["l"]=> string(4) "blue"
  }
}

如何更改内部数组的键?比如说,我想将n"更改为name",将l"更改为last_name".考虑到它可能发生,而不是数组没有特定的键.

How would I change the keys of the inside arrays? Say, I want to change "n" for "name" and "l" for "last_name". Taking into account that it can happen than an array doesn't have a particular key.

推荐答案

使用 array_walk

Using array_walk

array_walk($array, function (& $item) {
   $item['new_key'] = $item['old_key'];
   unset($item['old_key']);
});

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

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