在php中操纵数组

时间:2016-01-05 05:57:16

标签: php codeigniter

我使用join从两个表中获取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)
        {


        }   

我不想要重复的结果。我想要带有问题名称的结果及其选项。

2 个答案:

答案 0 :(得分:0)

两个选项:

  1. GROUP_CONCAT(如上文评论中所述)。有点像:

    $this->db->select('hbp_questions.*, GROUP_CONCAT(hbp_question_options.option) as options');
    
  2. 使用组合在一起的选项重建阵列。

    $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'];
    }  
    

答案 1 :(得分:0)

我建议您修复 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);