Как преобразовать индексный массив в ассоциативный массив - PullRequest
1 голос
/ 01 мая 2020

У меня есть такой массив:

array:10 [
       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"
   ]

, и я хочу получить такой массив:

array:2[
      'questions' => [
           0 => [
             'question_text' => '1. What is the first question?',
             'options' => [
                            0 => 'A. First answer',
                            1 => 'B. Second answer',
                            2 => 'C. Third answer',
                            3 => 'D. Forth answer'
                           ],
             'answer' => 'ANSWER: A'
             ],
         1 => [
             'question_text' => '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' => [
                            0 => 'A. Yes, I got it',
                            1 => 'B. No, I can’t',

                           ],
             'answer' => 'ANSWER: A'
             ],
       ]
 ]

Я хочу преобразовать этот индексный массив в многомерный массив. Как я могу преобразовать этот массив?

1 Ответ

2 голосов
/ 01 мая 2020

Это не будет этот большой код спагетти, даже если он не помещается в две строки:

$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

тем не менее, это, конечно, особая задача, и я согласен с предыдущим оратором в том, что массив указан необычно. Но если это так, вы должны жить с руководящими принципами ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...