PHP / Codeigniter比较对象(stdClass)和带array_intersect的字符串数组

时间:2017-05-19 14:09:33

标签: php arrays codeigniter session

我是PHP和Codeigniter的新手。

我正在尝试比较2个不同的数组(一个用字符串,一个用对象(stdClass),并计算它们的相似值,以计算结果。有没有可能解决这个问题,比如将对象转换为字符串或反之亦然?任何帮助将不胜感激。

这是我现在的一些代码:

Result.php

$countcorrectuser = count(array_intersect($_SESSION['correctanswers'], $_SESSION['useranswers']));
$countcorrect = count($_SESSION['correctanswers']);
$totalresult = $countcorrectuser / $countcorrect;
$this->session->set_userdata('totalresult', $totalresult);

Run.php

// $_SESSION['correctanswers']
$correctanswers = $this->Question_model->getAllAnswers();
$this->session->set_userdata('correctanswers', $correctanswers);

// $_SESSION['useranswers'] When the next question submit button is pressed
if(!isset($_SESSION['useranswers'])){
    $_SESSION['useranswers'] = array();
}
    $_SESSION['useranswers'][] = $this->input->post('useranswer'); 

Question_model.php

function getAllAnswers(){
    $query = $this->db->query('SELECT answer FROM question WHERE exam_id = \'' . $_SESSION['examid'] .'\'');
    return $query->result();
}

var_dump的示例($ _ SESSION ['correctanswers']);

array(4) { [0]=> object(stdClass)#25 (1) { ["answer"]=> string(6) "answer" } etc.

var_dump($ _ SESSION ['usersanswers']);

的示例
array(4) { [0]=> string(6) "answer" etc.

1 个答案:

答案 0 :(得分:2)

您的代码中的一些更改是为了便于阅读。它还使用Query Binding来提高可读性和安全性。

查询结果使用foreach循环创建一个与$_SESSION['usersanswers']结构匹配的数组。

function getAllAnswers()
{
    $sql = 'SELECT answer FROM question WHERE exam_id = ?';
    $answers = $this->db->query($sql, [$_SESSION['examid']])->result();
    $results = [];//empty array so there is always something to return
    foreach($answers as $answer){
        $results[] = $answer->answer;
    }
    return $results;
}