我有一个返回这样的数组:
[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
下一部分将在第一次出现之后获取字符串:直到下一次出现:并将其作为关键问题添加到同一数组($ newQuestions)中。
下一部分将是照片:,即我需要在照片后获取字符串:直到下一次出现逗号,在这种情况下,提取的字符串的和平将是c157。
我想在数组$ newQuestions
中添加名为photo的新键答案 0 :(得分: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 ) )
答案 1 :(得分:1)
我得到了自己的解决方案,至少在问题的一部分。我设法使用以下代码获取questionID:
$newQuestions = array();
foreach ($arrQuestions as $key => $question) {
$substring = substr($question, 0, strpos($question, ','));
$newQuestions[]['questionID'] = $substring;
}
我现在正试图为问题部分做同样的事情。我将更新此代码,以防其他人可能有类似的任务要完成。