2016-08-03 8 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

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

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

1 PARAM을 array_combine- 사용하여 키와 이러한 배열의 값을 결합 배열과 두 번째 인쇄의 키를 제공합니다 마지막으로 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));