开发者

array datastructure php problem

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 http://img85.imageshack.us/img85/170/query.png 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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜