views:

30

answers:

1

i want to make a new data structure using arrays for this query it will be like :

will start with a query and a code example

query i want to make a new data structure using arrays for this query it will be like :

//this is for the first headline
[46] => Array
        (
            [headline_name] => headline 1
            [score] => 50
            [questions] => Array
                (
                    [0] => Array
                        (
                            [question_id] => 136
                            [question_name] => question 3 , headline 1
                            [choice_0] => 0
                            [choice_1] => 0
                            [choice_2] => 0
                            [choice_3] => 0
                            [choice_4] => 0
                        ) ,
                    [1] => Array
                        (
                         ....
                        )
                )
        )

the code that i wrote wanting to achieve this result is :

foreach ($result as $row) {
  $data[$row->headline_id]= array( 
    'headline_name' => $row->headline_name ,
    'score' => $row->score,
  );
  $data[$row->headline_id]['questions'][] = array (
      'question_id'=>$row->question_id ,
      'question_name'=>$row->question_name ,
      'choice_0' => $row->choice_0 ,
      'choice_1' => $row->choice_1 ,
      'choice_2' => $row->choice_2 ,
      'choice_3' => $row->choice_3 ,
      'choice_4' => $row->choice_4             
  );  
}

the problem with it, it only shows the last question in each headline , in each loop in the questions array the array are not appended they overwrite each other


if i want to get it to work i have to delete i have to delete the lines for the score and headline_name , the code will be like this

foreach ($result as $row) {

  $data[$row->headline_id]['questions'][] = array (
      'question_id'=>$row->question_id ,
      'question_name'=>$row->question_name ,
      'choice_0' => $row->choice_0 ,
      'choice_1' => $row->choice_1 ,
      'choice_2' => $row->choice_2 ,
      'choice_3' => $row->choice_3 ,
      'choice_4' => $row->choice_4 
  );  

}

i want a solution to solve it with writing the headline_name and the score in the array

+1  A: 

the problem is that you reset the array in the second time when you enter to the loop by = ,

to solve it you need to add a little if

    if(!isset($data[$row->headline_id])) {
      $data[$row->headline_id]= array( 
        'headline_name' => $row->headline_name ,
        'score' => $row->score,
      );
  }

another issue : i recommend not to store this fields in this table is not normalize ,

headline_name
score
Haim Evgi
thanks , they are normalized i just did a query with a lot of inner joins , i didn't want to do multiple queries to get this table so i did a large one with some redundancy
Nadeem Khedr