我有一个数组的结果。我使用此正则表达式preg_split('/(?=[a-z\d]+\.(?!\d))/', $str, -1, PREG_SPLIT_NO_EMPTY)
Array
(
[0] => 1. What is foo?
[1] => a. foo1
[2] => b. foo2
[3] => c. foo3
[4] => d. foo4
[5] => 2. What is foo 2.1?
[6] => a. foo3
[7] => b. foo4
[8] => c. foo1
[9] => d. foo2
)
我想做的选择是他们知道他们属于哪个问题(即索引[1]到索引[4]属于索引[0])
答案 0 :(得分:1)
您可以使用array_chunk
(假设每个Q& A有1个问题和4个可能的答案)。索引0
永远是问题,然后你就有了答案。
array_chunk($array, 5);
您可以使用foreach
方法,并使用strpos
检查元素是否为问题。这会将每个问题和答案分组在其自己的数组中,插入0
键将成为问题。它比array_chunk
方法更灵活,因为它允许超过4个答案。
foreach($array as $key => $qanda) {
if( strpos($qanda, "?") ) {
$final[$key] = array($qanda);
$question = $key;
continue;
}
$final[$question][] = $qanda;
}
答案 1 :(得分:1)
你可以循环遍历数组并检查第一个字符:如果它是一个数字,那么必须有一个新的问题,当前条目后面的条目是答案,直到你再次得到一个数字。
$entries = array(
0 => '1. What is foo?',
1 => 'a. foo1',
2 => 'b. foo2',
3 => 'c. foo3',
4 => 'd. foo4',
5 => '2. What is foo 2.1?',
6 => 'a. foo3',
7 => 'b. foo4',
8 => 'c. foo1',
9 => 'd. foo2'
);
$questions = array();
$currentQuestion = null;
foreach($entries as $entry) {
if(is_numeric(substr($entry, 0, 1)) === true) {
$currentQuestion = $entry;
$questions[$entry] = array();
continue;
}
$questions[$currentQuestion][] = $entry;
}
var_dump($questions);
答案 2 :(得分:1)
还有一个问题是调整正则表达式并使用preg_match_all
:
$str = '1. What is Foo? a. foo1 b. foo2 c. foo3 d. foo4 e. foo5 2. What is foo 2.1? a. foo3 b. foo4 c. foo1 d. foo2';
preg_match_all('/(?:(\d+\..+?)|([a-z]+\..+?))(?=[a-z\d]+\.(?!\d)|\z)/', $str, $m);
# questions
print_r($m[1]);
Array
(
[0] => 1. What is Foo?
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] => 2. What is foo 2.1?
[7] =>
[8] =>
[9] =>
[10] =>
)
# multiple choices
print_r($m[2]);
Array
(
[0] =>
[1] => a. foo1
[2] => b. foo2
[3] => c. foo3
[4] => d. foo4
[5] => e. foo5
[6] =>
[7] => a. foo3
[8] => b. foo4
[9] => c. foo1
[10] => d. foo2
)