无法解析多阵列

时间:2014-10-24 10:12:03

标签: php arrays codeigniter

我正在尝试解析此数组以便将其保存在数据库中,但我不能这样做。

这是$this->input->post("question")产生的结果:

Array
(
    [1] => Array
        (
            [0] => question 1
            [answer] => Array
                (
                    [0] => answer 1
                    [1] => answer 2
                    [2] => answer 3
                    [3] => asnwer 4
                    [4] => answeer 5
                )

        )

    [2] => Array
        (
            [0] => queston 2
            [answer] => Array
                (
                    [0] => answer 21
                    [1] => answere 22
                    [2] => anwer 23
                    [3] => answer 24
                    [4] => answer 25
                )

        )

)

我试过了:

foreach ($this->input->post("question") as $questions) {
            foreach ($questions as $question) { 
                $data = array(
                    'question' => $question,
                );
                $this->db->insert('questions', $data);
                $question_id = $this->db->insert_id();
//another foreach to go throw answers

           }
}

只是为了检查我是否正确保存了问题,但我收到了这条消息:

  

消息:数组到字符串转换

1 个答案:

答案 0 :(得分:1)

首先,您正在获取该消息,因为您正在尝试将数组转换为字符串。

第二

foreach ($this->input->post("question") as $questions) {

}

第一级。在此之后,您将继续:

[1] => Array
(
   [0] => question 1
   [answer] => Array
    (
       [0] => answer 1
       [1] => answer 2
       [2] => answer 3
       [3] => asnwer 4
       [4] => answeer 5
    )

)

foreach ($this->input->post("question") as $questions) {
    foreach ($questions as $question) { 
        //here, $question is formed of 2 arrays
        //[0] => question 1 
        //[answer] => Array
        //  (
        //     [0] => answer 1
        //     [1] => answer 2
        //     [2] => answer 3
        //     [3] => asnwer 4
        //     [4] => answeer 5
        //  )

    }       
}

这是第二级。所以在那个foreach中,你应该使用:

$data = array(
   'question' => $question[0], // to get the question string
);

如果还需要更多信息,请与我们联系!

P.S:对于答案,你必须更深入一级,再做一个foreach。