2016-08-15 82 views
0

是否有關於PHP的方式,我可以進去$input陣列安排字符串的重新排列,並得到PHP陣列等效值

$input = array(3) { 
    [0]=> 
    string(3) "one" 
    [1]=> 
    string(3) "two" 
    [2]=> 
    string(5) "three" 
} 

然後使用了相當於$reference陣列參考

$reference = array(3) { 
    [0]=> 
    array(2) { 
     [0]=> 
     string(1) "2" 
     [1]=> 
     string(3) "two" 
    } 
    [1]=> 
    array(2) { 
     [0]=> 
     string(1) "3" 
     [1]=> 
     string(5) "three" 
    } 
    [2]=> 
     array(2) { 
     [0]=> 
     string(1) "1" 
     [1]=> 
     string(3) "one" 
    } 
} 

,並導致該$output陣列?

$output = array(3) { 
    [0]=> 
    string(3) "1" 
    [1]=> 
    string(3) "2" 
    [2]=> 
    string(5) "3" 
} 
+0

爲什麼不把參考數組做成這樣,如果我正確理解你的問題。 $參考=陣列( 「一個」=> 「1」, 「兩個」=> 「2」, 「三化」=> 「3」, ) –

+0

我在答覆中沒有什麼是走現有的數組並創建@TalhaMalik建議的內容。 – TecBrat

回答

0

你的用例心不是很清楚,但我想像你可以使用array_flip

$input = ['one','two','three']; 
$flipped = array_flip($input); 

echo $flipped['one']; //0 - arrays in php are zero based 
echo $flipped['three']; //2 - arrays in php are zero based 

如果你真的需要爲所描述的$reference陣列,那麼一個簡單的循環會做:

$reference=[]; 
foreach($input as $key=>$value) 
    $reference[]=[$key+1, $value]; 
1

這對我有效。

foreach ($reference as $value){ 
    $new_ref[$value[1]] = $value[0]; 
} 

foreach($input as $in){ 
    $output[]=$new_ref[$in]; 
} 

var_export($output); 

PHP Sandbox

我做的第一件事是做一個新的陣列是關鍵了相匹配的輸入,然後我分配了這些鍵的輸出數組中的項目的價值。

1

您可以使用array_column將第二列(「2」,「3」等)重新索引您的參考數組。

$words = array_column($reference, null, 1); 

然後通過查找重建索引數組中對應於每個值從$input鍵讓你的輸出。

$output = array_map(function($x) use ($words) { return $words[$x][0]; }, $input);