To understand an array in PHP when given the other variable in the array

前端 未结 2 1717
庸人自扰
庸人自扰 2020-12-20 07:55

Please, see Cha\'s answer where we are pretty close the final solution. We are debugging the code with these data

  1. database in PostgreSQL
  2. test sql-quer
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-20 08:44

    If you want to add more information about each question, you can simply add to $end_array[1]. This is the array my first foreach statement creates:

    // The end result turns out to be something like this:
        array(
              1 => array(
                           'tags' => array(
                                          0 => "php",
                                          1 => "sql"),
                        )
             );
    

    and the code in the question initially

        // Go through each Tag
        while( $tags_and_Qid = pg_fetch_array( $result_tags )) {
            // Add the Tag to an array of tags for that question
            $end_array [ $tags_and_Qid['question_id'] ] ['tag'] [] = $tags_and_Qid['tag'];
        }
    
        // First compile the Data
        // Go through each question
    
        while( $titles_and_Qid = pg_fetch_array( $result_titles ) ) {
            echo ("
    " . $titles_and_Qid['title'] // Problem here! // How can you print the titles such that // they are assigned to each tag -set? ); $i = 0; // Then Loop Through each question foreach( $end_array as $tags_and_Qid['question_id'] => $tags_and_Qid['tag'] ) { echo ("\n\nITERATION NUMBER IS " . $i); // The code is buggy here // For instance, we get 9 iterations for 3 questions // Create the starting HTML echo ("
    "); // Go through each tag // not sure about this foreach( $end_array[$tags_and_Qid['question_id']] ['tag'] as $tag ) { echo ( "" ); } // end the html echo '
    '; $i++; } echo ("
    "); } // to end the list of questions echo ("
    " ); } ?>

提交回复
热议问题