Это не будет этот большой код спагетти, даже если он не помещается в две строки:
$array = [
1 => "1. What is the first question?",
2 => "A. First answer",
3 => "B. Second answer",
4 => "C. Third answer",
5 => "D. Forth answer",
6 => "ANSWER: A",
7 => "2. What is the second question? This question is of multiple lines and it can
go into 2 or 3 or 4 lines, but make sure you import it correctly.",
8 => "A. Yes, I got it",
9 => "B. No, I can’t",
10 => "ANSWER: A",
];
$questionIndex=-1;
$target_array = ['questions' => []];
foreach ($array as $entry) {
if (strpos($entry, ".")!==false) {
list ($left,$right) = explode (".",$entry);
if (is_numeric(trim($left)))
$target_array['questions'][++$questionIndex] = ['question_text' => $entry, 'options' => [], 'answer' => ''];
else
$target_array['questions'][$questionIndex]['options'][] = $entry;
} else {
$target_array['questions'][$questionIndex]['answer'] = $entry;
}
}
var_dump ($target_array);
приводит к:
array(1) {
["questions"]=>
array(2) {
[0]=>
array(3) {
["question_text"]=>
string(30) "1. What is the first question?"
["options"]=>
array(4) {
[0]=>
string(15) "A. First answer"
[1]=>
string(16) "B. Second answer"
[2]=>
string(15) "C. Third answer"
[3]=>
string(15) "D. Forth answer"
}
["answer"]=>
string(9) "ANSWER: A"
}
[1]=>
array(3) {
["question_text"]=>
string(158) "2. What is the second question? This question is of multiple lines and it can
go into 2 or 3 or 4 lines, but make sure you import it correctly."
["options"]=>
array(2) {
[0]=>
string(16) "A. Yes, I got it"
[1]=>
string(16) "B. No, I can’t"
}
["answer"]=>
string(9) "ANSWER: A"
}
}
}
http://sandbox.onlinephpfunctions.com/code/081dbbdd66c160f303d9a99bbd01806a7adf7708
тем не менее, это, конечно, особая задача, и я согласен с предыдущим оратором в том, что массив указан необычно. Но если это так, вы должны жить с руководящими принципами ...