2016-09-21 90 views
-3

我有它返回像這樣的數組:如何從數組元素中獲取部分字符串,並將其插入到另一個數組中?

[44] => 165,text:Where is this city:,photo:c157,correct:0,answers:[{text:Pery.,correct:true},{text:Cuba.,correct:false},{text:Brazil.,correct:false}]},{ 

我想獲得所有從字符串開頭的數字,直到在數組元素值逗號的第一次出現。在這種情況下,這將是數字165,我想將該數字放在另一個名爲$ newQuesitons的數組中作爲關鍵questionID

下一部分將在第一次出現之後獲取字符串:直到下一次出現:and add它成爲與關鍵問題相同的數組($ newQuestions)。

下一部分將是照片:,這是我需要得到的照片後的字符串:直到下一次出現的逗號,在這種情況下,提取的字符串和平將c157。

我想補充一點,作爲新的關鍵命名照片在數組中$ newQuestions

+0

很好聽。你曾嘗試這麼做的嗎? –

+0

我不知道如何搜索數組鍵值的一部分。 – user2417624

+0

如果你能告訴我如何從數組的值開始獲得所有數字,直到第一次出現逗號,我想我可以從那裏找到我的路 – user2417624

回答

1

我想,這也許能夠幫助你

<?php 
$input = '165,text:Where is this city:,photo:c157,correct:0'; 

//define our new array 
$newQuestions = Array(); 
//first part states we need to get all the numbers from the beginning of  the string until the first occurence of a ',' as this is our array key 
//$arrayKey[0] is our arrayKey 
$arrayKey = explode(',',$input); 

//second part requires us to loop through the array and split up the strings by comma and colon 
foreach($arrayKey as $data){ 
//split each text into 2 by the colon 
    $item = explode(':',$data); 
    //we are only interested in items that have a colon in them, if we split it and the input has no colon, the count would be 0, so this check is used to ignore those 
    if(count($item) > 0) { 
     //now we can build our array 
     $newQuestions[$arrayKey[0]][$item[0]] = $item[1]; 
    } 

} 
//output array 
print_r($newQuestions); 

?>  

我不完全理解的輸入陣列,上面的代碼很可能不得不進行調整,但至少它會給你一些邏輯。

這樣做的產量爲:Array ([165] => Array ([165] => [text] => Where is this city [photo] => c157 [correct] => 0))

+0

感謝您的幫助,但我覺得我會在調整過程中迷路。我將嘗試通過字符串操作來使用解決方案,並且還會看到我可以在代碼中使用的內容。再次感謝。 – user2417624

+0

調整隻是在輸入,我相信你正在使用二維數組作爲您的輸入。這個代碼應該仍然有效,但在閱讀「答案」數組時可能會失敗。無論如何,請仔細研究一下。我會稍後再檢查,看看你是如何得到 – IsThisJavascript

1

我得到我自己的解決方案,至少在問題的一部分。我管理使用下面的代碼來獲取questionID:

$newQuestions = array(); 

foreach ($arrQuestions as $key => $question) { 
    $substring = substr($question, 0, strpos($question, ',')); 
     $newQuestions[]['questionID'] = $substring; 
} 

我現在試圖做同樣的事情的問題的一部分。如果別人可能有類似的任務要完成,我會更新此代碼。

+0

我建議刪除這個問題,並把它放在你問的問題,因爲它最有可能在那裏看到。 – IsThisJavascript

相關問題