2016-09-21 38 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

相关问题