【发布时间】:2016-04-07 01:50:15
【问题描述】:
所以我有这样的二维数组:
Array
(
[0] => Array
(
[0] => a
[1] => d
[2] => c
[3] => e
[4] => b
)
[1] => Array
(
[0] => c
[1] => b
[2] => e
[3] => a
[4] => d
)
[2] => Array
(
[0] => e
[1] => c
[2] => b
[3] => d
[4] => a
)
)
我会把它做成一维的,然后像这样内爆
a,d,c,e,b; c,b,e,a,d; e,c,b,d,a;
这是我在模型中的代码(我使用 PHP 和 CodeIgniter 作为我的框架):
从二维数组转换为一维并转为字符串
private function _randomize_answer($id)
{
$alphabet = '';
$answer = '';
// Get from database
// The result is ID question array
$question = $this->select_temp_question($id)['question'];
// $question output is ID questions list with semicolon as the delimeter
// Output result is : 1; 2; 3; 4; 5; . . .
$question = explode('; ', $question);
// count($question) is = 50
for ($i = 0; $i < count($question); $i++)
{
// Get from database
// The output is 2-dimensional array
$options[$i][0] = 'a' . $this->select_final_question($question[$i])['option_a'];
$options[$i][1] = 'b' . $this->select_final_question($question[$i])['option_b'];
$options[$i][2] = 'c' . $this->select_final_question($question[$i])['option_c'];
$options[$i][3] = 'd' . $this->select_final_question($question[$i])['option_d'];
$options[$i][4] = 'e' . $this->select_final_question($question[$i])['option_e'];
// Shuffling array
shuffle($options[$i]);
// FOR looping, to get the first character / getting the alphabet
for ($j = 0; $j < count($options[$i]); $j++)
{
$alphabet[$i][$j] = substr($options[$i][$j], 0, 1);
}
}
// FOR looping, to convert from 2-dimensional array into 1-dimensional array
// and convert again into string with comma as the glue
// and semicolon as the delimeter per array
//
// Output result is : a,d,c,e,b; c,b,e,a,d; e,c,b,d,a; . . .
for ($i = 0; $i < count($question); $i++)
{
$answer .= implode(',', $alphabet[$i]) . '; ';
}
// To remove the end of the semicolon
$answer = substr($answer, 0, -2);
// Return the answer as string
return $answer;
}
当我尝试将此函数回显到控制器中时,输出成功且没有错误,例如a,d,c,e,b; c,b,e,a,d; e,c,b,d,a; . . .
但是当我尝试插入数据库时,记录只是第一个数组,它只是a,d,c,e,b,而不是所有数组。
添加到数据库
public function set_temp_question($id)
{
$this->object = array(
'idtemp_question' => NULL,
'id_exam' => $this->_row_exam($id)->id_exam,
'question' => $this->_randomize_question($id),
'answer' => $this->_randomize_answer($id),
);
$this->db->insert('tbtemp_question', $this->object);
}
这两个函数都放在同一个模型文件中。
【问题讨论】:
-
您发布的代码无关紧要,只显示插入开始的部分,您已经说过那里的位工作正常,并且旁注,只需使用活动记录
-
你可以
foreach你的数组并使用array_push创建一个新数组来包含它们 -
@Ghost 当我尝试回显到控制器时工作正常,但是当我尝试将其插入数据库时,成功插入数据库的记录只是第一个数组
-
所以您问的是向数据库中插入数据的问题,但您没有向我们展示该代码?!
-
有一个最简单的方法可以解决您的问题....您可以使用
insert_batch()并简单地提供数组...这里是您检查的链接ellislab.com/codeigniter/user-guide/database/active_record.html
标签: php arrays algorithm codeigniter