2016-08-03 142 views
0

我想知道,如何根据值对每个数组元素执行函数。基于值组合两个数组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,但没有得到它。 :(

+2

尝试'array_combine(array_keys($ array1),array_values($ translation));'? – jitendrapurohit

+0

@jitendrapurohit如果数组中有不同数量的元素,它会工作。 –

+0

哦,这么认为,刚刚评论没有尝试。谢谢 – jitendrapurohit

回答

0
<?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 
) 
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); 
0
使用

array_combine-

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

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

第一PARAM合并键和这些阵列的值给出了阵列和第二打印所述的按键值,最后与array_combine结合使用。

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