简体   繁体   English

用php交换多维数组键

[英]Swap multidimensional array keys with php

I have two keys and want to swap them in a multidimensional array. 我有两个键,想在多维数组中交换它们。

I Have referred these Swap array values with php , How to swap two values in array with indexes? 我已经用php引用了这些Swap数组值如何用索引交换数组中的两个值? references but didn't get any help. 参考,但没有任何帮助。

I have this array, 我有这个数组

[
    'box-a' => 'email',
    'box-b' => 'job',
    'box-c' => 'company',
    'box-d' => 'candidate',
    'box-e' => 'calender',
    'box-f' => 'smartlist',
    'box-g' => 'analytics',
]

And I want to swap two array keys, box-b and box-e but the array values should remain as it is. 我想交换两个数组键box-bbox-e但数组值应保持原样。

I have tried this, 我已经试过了

list($array[$swap_a], $array[$swap_b]) = array($array[$swap_b], $array[$swap_a]);

But didn't get success. 但是没有成功。 Where am I wrong? 我哪里错了?

Try to use temp array, like this: 尝试使用临时数组,如下所示:

$a = [
'box-a' => 'email',
'box-b' => 'job',
'box-c' => 'company',
'box-d' => 'candidate',
'box-e' => 'calender',
'box-f' => 'smartlist',
'box-g' => 'analytics',
];

$temp = $a['box-e'];
$a['box-e'] = $a['box-b'];
$a['box-b'] = $temp;

You can use array_replace() in a one-liner, and avoid using temporary data storage. 您可以array_replace()使用array_replace() ,并避免使用临时数据存储。

Code: ( Demo ) 代码:( 演示

$a = [
'box-a' => 'email',
'box-b' => 'job',
'box-c' => 'company',
'box-d' => 'candidate',
'box-e' => 'calender',
'box-f' => 'smartlist',
'box-g' => 'analytics'
];

var_export(array_replace($a,['box-b'=>$a['box-e'],'box-e'=>$a['box-b']]));

Output: 输出:

array (
  'box-a' => 'email',
  'box-b' => 'calender',
  'box-c' => 'company',
  'box-d' => 'candidate',
  'box-e' => 'job',
  'box-f' => 'smartlist',
  'box-g' => 'analytics',
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM