根据值 php 组合两个数组

Combining two arrays based on values php

我想知道,如何根据值对每个数组元素执行函数。

例如,如果我有两个数组:

[
  0 =>  'gp', 
  1 =>  'mnp', 
  2 =>  'pl', 
  3 =>  'reg'
]

$translation = [
    'gp' => 'One',
    'mnp' => 'Two',
    'pl' => 'Three',
    'reg' => 'Four',
    'other' => 'Five',
    'fs' => 'Six'
];

如何获得

    [ 
      0 =>  'One', 
      1 =>  'Two', 
      2 =>  'Three',
      3 =>  'Four'
   ]

?

我使用 foreach 进行了管理,但我相信有一些更有效的方法可以做到这一点。我试着玩弄 array_walkarray_map,但没搞定。 :(

<?php

$arr = [
  0 =>  'gp', 
  1 =>  'mnp', 
  2 =>  'pl', 
  3 =>  'reg'
];

$translation = [
    'gp' => 'One',
    'mnp' => 'Two',
    'pl' => 'Three',
    'reg' => 'Four',
    'other' => 'Five',
    'fs' => 'Six'
];

$output = array_map(function($value)use($translation){
  return $translation[$value];
  }, $arr);

print_r($output);

输出:

Array
(
    [0] => One
    [1] => Two
    [2] => Three
    [3] => Four
)
<?php 
$data = array('gp','mnp','pl','reg');
$translation = array( 'gp' => 'One','mnp' => 'Two','pl' => 'Three','reg' => 'Four','other' => 'Five','fs' => 'Six');
$new  = array_flip($data);// chnage key value pair
$newArr = array();
foreach($new as $key=>$value){
    $newArr[]= $translation[$key];  
}

echo "<pre>";print_r($newArr);

使用array_combine-

组合这些数组的键和值
$sliced_array = array_slice($translation, 0, count(array1));

array_combine(array_keys($array1), array_values($sliced_array));

第一个参数给出数组的键,第二个参数打印值。最后结合array_combine.

$toto1 = [
  0 =>  'gp', 
  1 =>  'mnp', 
  2 =>  'pl', 
  3 =>  'reg'
];

$toto2 = [
    'gp' => 'One',
    'mnp' => 'Two',
    'pl' => 'Three',
    'reg' => 'Four',
    'other' => 'Five',
    'fs' => 'Six'
];

$result = array_slice(array_merge(array_values($toto2), $toto1), 0, count($toto1));