2016-12-03 53 views
-2

我怎么能把它分成多维数组。分割测验查询

  1. 问题1

    A)回答1
    B)回答2

  2. 问题2

    A)回答1
    B)回答2

+1

请编辑你的问题 –

+0

刚刚做到了。你能帮我吗? –

+1

你想拆分什么?给定格式的字符串? – invisal

回答

0
function parseQuestions($str) { 
     $str = preg_replace("/\r|\n|\t/", " ", $str); // Remove line breaks and replace with spaces 

     $split_questions = preg_split("/\d+\./", $str, -1, PREG_SPLIT_NO_EMPTY); // An array containing each question and their answers as a string 
     $split_answers = array(); // Array that will contain the final arrays with questions and their answers 

     foreach($split_questions as $qkey => $q) { // Parses the question and splits it so [0] is the question and everything following are answers 
      $split_answers[$qkey] = preg_split("/[a-zA-Z]\)/", $q); 

      foreach($split_answers[$qkey] as $akey => $a) { // Loop that goes through each of the answers and trims off whitespace 
       $split_answers[$qkey][$akey] = trim($a); 
      } 
     } 

     return $split_answers; 
    } 

此函数将返回一个包含您的问题的数组。数组的索引0将成为你的问题,所有后续索引将成为答案。例如,当提供时字符串:

1. What is the first letter of the alphabet? 
A) no 
B) 17 
C) A 

2. What time is it? 
A) 7:02 
B) Night Time 
C) I don't know 
D) Hammer Time! 

该函数将返回一个数组具有以下结构:

[ 
    [ 
     "What is the first letter of the alphabet?", 
     "no", 
     "17", 
     "A" 
    ], 
    [ 
     "What time is it?", 
     "7:02", 
     "Night Time", 
     "I don't know", 
     "Hammer Time!" 
    ] 
] 

空白移除并忽略,因此不应该影响到返回的数组。

+0

谢谢。这正是我所寻找的,但还有另一个问题。如果我在答案中有一些“(”),他会分开答案,如何解决它? –

+0

你得到的越具体,它就越不友好,触发这个的是你有一个字母后跟''' 。如果你的问题只有大写字母来表示每个选项(即'A)','B)'和'C)'而不是'd)'),那么改变'/ [a-zA-Z] \)/ '到'/ [AZ] \)/'。如果您的问题最多只有4个答案,那么答案是A,B,C和D,那么您可以将'/ [A-Z] \)/'更改为'/ [A-D] \)/'。如果你有一个例子,你需要被允许可以帮助我。如果这需要允许任何答案组合,那么您需要由谁提出问题来设置一些指导方针 – bugfroggy

0

PHP的代码可能是这样的:

$array = [ 
'q1' => [ 
     'Ans1', 
     'Ans2' 
     ], 
'q2' => [ 
     'Ans1', 
     'Ans2' 
     ]  

];