2017-04-22 34 views
1

所以我的問題可能不是最好的,所以很抱歉。
我有一個字符串數組,並希望在另一個數組的幫助下使用它作爲順序/鍵寫入文本。這是輸入:如何用數組的字符串「寫入」文本?

$words =["I","am","cool"]; 
$order =["2","0","1","0","1","2"]; 
//var_export($words); 
// array (
//  0 => 'I', 
//  1 => 'am', 
//  2 => 'cool', 
//) 

我想用$爲了作爲某種關鍵的重新排列$話這樣我就可以得到如下的輸出:

"Cool I am I am cool" 

幫助是非常讚賞,謝謝:)

回答

1

使用的$order值作爲$words鍵。

$words =["I","am","cool"]; 
$order =["2","0","1","0","1","2"]; 
$output = ''; 
foreach($order as $key) { 
    $output .= $words[$key] . ' '; 
} 
echo ucfirst(trim($output)); 

演示:https://eval.in/780785

empty($real_key)是檢查它是否是第一次迭代。也可以是== 0

+0

一個問題。當我運行代碼時,出現一個錯誤消息,說明我的$ order中的每個數字都是未定義的(index undefined:1)。我的$訂單是用$ order = explode(「\ n」,$ string)創建的;每個數字都是字符串中的一個段落。爲什麼它不起作用?謝謝你的解決方案:) – staffblast

+0

你可能有空白嗎?使用'trim'應該修復它,https://eval.in/780816。 – chris85

+0

是的,現在它工作。非常感謝!!!有一個美好的一天:) – staffblast

0

從一個空數組開始。 然後遍歷order數組並將字數組部分添加到新字符串中。

$my_string= array(); 

    foreach ($order as $index) { 
     $index = int($index); 
     $my_string[] = (isset($words[ $index])) ? $words[ $index ] : ''); 
    } 

$my_string = implode(' ', $my_string); 
echo my_string; 
0

對訂單進行迭代並將其值用作單詞的關鍵字;轉換下面的代碼到PHP它應該是很簡單...

foreach (string orderIndexString in order) { 
    int orderIndexInt = System.Convert.ToInt16(orderIndexString); // convert string to int 
    if(orderIndexInt < 0 || orderIndexInt >= words.Length) 
     continue; 

    print (words[orderIndexInt]); // either print or add it to another string 
    } 
1

我會建議使用array_mapjoin

沒有必要

  • 副作用的手動迭代使用foreach
  • if陳述或三元表達式
  • 變量再分配
  • 使用.
  • 檢查數組字符串連接長度

在這裏,我們去

function map_indexes_to_words ($indexes, $words) { 
    $lookup = function ($i) use ($words) { 
    return $words[(int) $i]; 
    }; 
    return join(' ', array_map($lookup, $indexes)); 
} 

$words = ["I","am","cool"]; 
$order = ["2","0","1","0","1","2"]; 

echo map_indexes_to_words($order, $words); 
// 'cool I am I am cool' 
相關問題