php一个数组的键,PHP切换数组的两个键

标签:php

我有一个数组:

$array['text6'] = array(

'elem2' => 'text2',

'elem3' => 'text3',

'elem4' => 'text4',

'elem5' => 'text5'

'elem6' => 'text6'

);

我想以这种方式更改,例如text6键与其他键:

$name_key = 'elem4';

// something action here

// and final array:

$array['text4'] = array(

'elem2' => 'text2',

'elem3' => 'text3',

'elem5' => 'text5'

'elem6' => 'text6'

);

我怎么能这样做?我有105个数组,我需要以相同的方式更改每个数组,所以当数组看起来:

$array['text6'] = array(

'elem2' => 'text2',

'elem3' => 'text3',

'elem4' => 'text4',

'elem5' => 'text5'

'elem6' => 'text6'

);

$array['othertext6'] = array(

'elem2' => 'othertext2',

'elem3' => 'othertext3',

'elem4' => 'othertext4',

'elem5' => 'othertext5'

'elem6' => 'othertext6'

);

我想用第三个键更改主键(键 – >>’elem4′),它应该在每个数组中生成(不同的beetwen数组只在值中,键总是相同的):

$name_key = 'elem4';

// action...

$array['text4'] = array(

'elem2' => 'text2',

'elem3' => 'text3',

'elem5' => 'text5'

'elem6' => 'text6'

);

$array['othertext4'] = array(

'elem2' => 'othertext2',

'elem3' => 'othertext3',

'elem5' => 'othertext5'

'elem6' => 'othertext6'

);

我怎么能这样做?

解决方法:

如果我理解正确,您希望将数组中元素的键设置为第二个数组中元素的值,该数组本身就是顶级数组中第一个键的值.此外,您要从第二级数组中删除该元素.

顶级数组的键是否总是用相同的键更改为第二级的值?

也就是说,’elem4’总是成为顶级数组关键值的关键吗?

如果是这样,你可以这样做:

首先将所有数组放入一个大数组中,以便循环遍历它们.

$list = array($array['text4'], $array['text5'], ... (all your other arrays here));

然后,

$name_key = 'elem4';

foreach ($list as $k => $v) {

$new_key = $v[$name_key];

unset ($v[$name_key]);

$list[$new_key] = $v;

unset ($list[$k]);

}

标签:php

来源: https://codeday.me/bug/20190702/1356432.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值