编辑:
我想要一个像这样的结构
'categories' => [
[
'name' => "science" ,
'questions' => [
[
'question' => 'C1_Q2',
'answer' => 'C1_A2',
],
[
'question' => 'C1_Q3',
'answer' => 'C1_A3',
]
]
]
但借助循环
我正在尝试创建一个问卷,其中需要完成3个步骤
创建3个数组
1.categories - 2d - like category [“science”] [“questions”]
2.questions
3.answers
步骤1.在问题数组中添加10个问题,并在答案数组中添加10个答案
第2步。问题数组的第5个问题应插入类别[“科学”] [“问题”]和类别[“科学”]的5个答案 [“答案”]
我创建了问答数组,并在其中添加了10,10个元素。但是没有按照步骤2成功添加其元素。我尝试了很少的逻辑
$Category=array();
$Q=array();
$A=array();
for($i=1;$i<=10;$i++)
{
$Q[] = "Question post".$i;
$A[] = "Answer post".$i;
//if($i==5)
//{
// array_push($Category,$Q[i]);
// break;
//} ---logic not working
}
//array first 5 Questions to category array
/*
for($i=1;$i<=5;$i++)
{
//$Category[]=$Q[i];
array_push($Category,$Q[i]);
}
*/ -- not working
print_r($Category);
任何建议或帮助将不胜感激
答案 0 :(得分:0)
试试这个:
$questions = [];
$answers = [];
for($i=1; $i <= 10; $i++) {
$questions[] = 'Question post' . $i;
$answers[] = 'Answer post' . $i;
}
$categories = ['science', 'something', 'else'];
$result = [];
foreach ($questions as $index => $question) {
if ($index % 5 != 0 || $index == 0) {
$category = current($categories);
} else {
$category = next($categories);
}
$result[$category][] = ['question' => $question, 'answer' => $answers[$index]];
}
var_dump($result);