我使用联接从两个表中获取Result。它给了我这样的结果。我想根据类似的操作结果:
具有多个结果的问题名称。
Array
(
[0] => stdClass Object
(
[id] => 1
[question_id] => 1
[option] => kk
[created_at] => 0000-00-00 00:00:00
[updated_at] => 2016-01-04 17:19:47
[deleted_at] =>
[question] => whats ur name
[status] => 0
)
[1] => stdClass Object
(
[id] => 1
[question_id] => 1
[option] => bb
[created_at] => 0000-00-00 00:00:00
[updated_at] => 2016-01-04 17:19:47
[deleted_at] =>
[question] => whats ur name
[status] => 0
)
[2] => stdClass Object
(
[id] => 2
[question_id] => 2
[option] => anish
[created_at] => 0000-00-00 00:00:00
[updated_at] => 2016-01-04 18:38:38
[deleted_at] =>
[question] => whats ur father name
[status] => 0
)
[3] => stdClass Object
(
[id] => 2
[question_id] => 2
[option] => satish
[created_at] => 0000-00-00 00:00:00
[updated_at] => 2016-01-04 18:38:38
[deleted_at] =>
[question] => whats ur father name
[status] => 0
)
)
这是我的代码:
public function question_get() {
$this->db->select('*');
$this->db->from('hbp_question_options');
$this->db->join('hbp_questions', 'hbp_questions.id = hbp_question_options.question_id');
$query = $this->db->get();
$result = $query->result();
foreach($result as $results)
{
}
我不想要重复的结果。我想要问题名称和他们的选项的结果。
我建议您修复SQL查询,而不是使用PHP进行过滤。如果您要检索大量数据,这确实可能会减慢应用程序的速度。
但是,如果您坚持通过PHP来完成,这段代码可能会对您有所帮助。
$ids = array();
// $fetchResult is the result of your array on your post.
$finalResult = array_filter($fetchResult, function($obj) use (&$ids)
{
//$id = $obj['id'] || $obj.id;
$id = $obj['id']; // Or in your case, you might need to access it like `$obj.id`
if (!in_array($id, $ids))
{
$ids[] = $id;
return $obj;
}
});
var_dump($finalResult);
两个选项:
-
GROUP_CONCAT
(如上文评论中所述)。大致如下:$this->db->select('hbp_questions.*, GROUP_CONCAT(hbp_question_options.option) as options');
-
使用分组在一起的选项重新生成阵列。
$grouped_results = []; foreach($results as $result){ if (!isset($grouped_results[$result['question_id'])) { $grouped_results['questionid'] = [ 'question_id' => $result['question_id'], 'question' => $result['question'], 'status' => $result['status'], 'options' => [], ]; } $grouped_results['question_id']['options'][$result['id']] = $result['option']; }