2016-08-03 139 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));