0

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

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

[
  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_walkand array_map,但没有得到它。:(

4

4 回答 4

1
<?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
)
于 2016-08-03T09:37:58.767 回答
0
<?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);
于 2016-08-03T09:38:04.303 回答
0

使用 array_combine- 组合这些数组的键和值

$sliced_array = array_slice($translation, 0, count(array1));

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

第一个参数给出数组的键,第二个打印值。最后将它与array_combine 结合起来。

于 2016-08-03T09:39:28.747 回答
0
$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));
于 2016-08-03T09:43:49.743 回答