How to retrieve data from mysql in a parent child format in php?

Viewed 245

I have two tables,

question                  question choices

id question             id  question_id  choice
1    aaaa                1      1         ccc
2    bbbb                2      1         ddd
                         3      1         eee

I get the data using left join query using php, when I print the data it looks like this,

Array
(
    [id] => 1
    [question] => aaa
    [question_id] => 1
    [choice] => ccc
)
Array
(
    [id] => 1
    [question] => aaa
    [question_id] => 1
    [choice] => ddd
)
Array
(
    [id] => 1
    [question] => aaa
    [question_id] => 1
    [choice] => eee
)

But i want to display something like,

Array
    (
        [id] => 1
        [question] => aaa,
           array
              (
                [question_id] => 1
                [choice] => ccc
              )
           array
              (
                [question_id] => 1
                [choice] => ddd
              )
    )

I want to display the child table datas inside the parent so that i can prevent the question from repeating.

How can i make it using core php?

2 Answers

You need not to use the join query, just fetch seperately.

    //$questions; $question_choices;
    $questions = array_column($questions,null,'id');
    foreach($question_choices as $question_choice){
        $questions[$question_choice["question_id"]][] = $question_choice;
    }

It is just simple. You need to loop over response data and formate it according to your needs. Here is the example by using the sample array you provide in question.

    $response_array = array(
  array
  (
      'id' => 1,
      'question' => 'aaa',
      'question_id' => 1,
      'choice' => 'ccc'
  ),
  array
  (
      'id' => 1,
      'question' => 'aaa',
      'question_id' => 1,
      'choice' => 'ddd'
  ),
  array
  (
      'id' => 1,
      'question' => 'aaa',
      'question_id' => 1,
      'choice' => 'eee'
  )
);
$result_array = array();
foreach ($response_array as $key => $value) {
    $result_array[$value['id']]['id'] = $value['id'];
    $result_array[$value['id']]['question'] = $value['question'];


    $result_array[$value['id']][] = array(
        'question_id' => $value['question_id'],
        'choice' => $value['choice']
    ); 
}

// it will print the array to check response
echo '<pre>';print_r($result_array);
Related