PHP交换数组中的两个键

4

我有一个数组:

$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'
    );

我可以帮助你翻译。这篇文章涉及到IT技术。你需要更改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'),并且它应该在每个数组中进行更改(数组之间的区别仅在于值,键始终相同):

$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'
);

我该怎么做呢?


这是错误的方法。您需要嵌套列表(节点的子级)。 - Deep
看这里,我编辑了我的问题。主要关键字始终在数组中('elem6' => 'text6')。我想删除主键并从数组中更改为另一个键,然后 - 从数组中删除此键。 - NewbieUser
请标记哪个答案解决了您的问题,@新手用户 - Tim
1个回答

2
如果我理解正确,您想将数组中的一个元素的键设置为第二个数组中的元素值,该值本身是顶层数组中第一个键的值。此外,您想从第二级数组中删除该元素。
顶层数组的键是否总是更改为具有相同键的第二级别的值?
也就是说,“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]);
}

1
使用$name_key代替硬编码的'elem4' - Barmar
你确定这是一个好的解决方案吗?主数组中的名称和值对于我非常重要。我认为,在你的解决方案中,你删除了所有的键,对吧? - NewbieUser
1
@NewbieUser,在我的解决方案中,我正在从每个二级数组中删除键“elem4”,并将该数组的键设置为顶级数组中的“elem4”(或$name_key)的值。如果您想保留第二级数组中的该元素('elem4'),则可以删除以下行:unset($v[$name_key]); - Tim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接