合并两个数组,将第一个数组值保存为键,将第二个数组值保存为值

时间:2021-09-08 19:16:10

Basically i have an array of key mappings (actually translations) and an array of data values. I want to essentially replace the keys of the second array with the values of the first array.

基本上我有一组键映射(实际上是翻译)和一组数据值。我想基本上用第一个数组的值替换第二个数组的键。

E.G.:

例如。:

$array1 = array(
  'key1' => 'newkey1',
  'key2' => 'newkey2',
  'key3' => 'newkey3',
  'key4' => 'newkey4'
);

$array2 = array(
  'key1' => 'data1',
  'key2' => 'data2',
  'key3' => 'data3',
  'key4' => 'data4',
  'key5' => 'data5',
  'key6' => 'data6'
);

$result = array(
  'newkey1' => 'data1',
  'newkey2' => 'data2',
  'newkey3' => 'data3',
  'newkey4' => 'data4'
);

Edit: Added excess data to second array

编辑:向第二个数组添加多余数据

1 个解决方案

#1


7  

If you're sure that the number of elements in both the arrays are same, you can simply use array_combine():

如果您确定两个数组中的元素数相同,则可以使用array_combine():

$result = array_combine($array1, $array2);

If your second array contains excess elements, then you could use array_intersect_key() to remove them before using array_combine():

如果你的第二个数组包含多余的元素,那么在使用array_combine()之前你可以使用array_intersect_key()删除它们:

$values = array_intersect_key($array1, $array2);
$result = array_combine($array1, $values);

Demo

演示

#1


7  

If you're sure that the number of elements in both the arrays are same, you can simply use array_combine():

如果您确定两个数组中的元素数相同,则可以使用array_combine():

$result = array_combine($array1, $array2);

If your second array contains excess elements, then you could use array_intersect_key() to remove them before using array_combine():

如果你的第二个数组包含多余的元素,那么在使用array_combine()之前你可以使用array_intersect_key()删除它们:

$values = array_intersect_key($array1, $array2);
$result = array_combine($array1, $values);

Demo

演示