PHP repeats repeating lines only once

I have 2 tables. One table is “headings” and contains headings, and the other is “headings” and contains subheadings that (and should) be classified under headings and should have a corresponding heading. A subtitle can have only one title, and many subtitles can have the same title. Therefore, consider the following format:

--Table heading

heading_id heading
1           H1
2           H2
3           H3


--Table sub_heading

sub_head_id sub_heading heading_id
1           SH1             1
2           SH2             1
3           SH3             2
4           SH4             3
5           SH5             2
6           SH6             4

What I would like to do is query the database only once and get all the sub_headings and their respective headers (using Inner Join?) And display the header only once and list all the sub_headings listed in their respective header. So, in practice, I would like to show OUTPUT RESULT AS :

H1
--SH1
--SH2

H2
--SH3
--SH5

H3
--SH4

H4
--SH6

, , , , . , .

.. header_id, , , . sub_headings. ( ) , , , , . , 50 , , , . , . .

, , - , , . .

+3
2
$query = "SELECT
    h.heading,
    s.sub_heading 
FROM
    heading h
LEFT JOIN
    sub_heading s
ON
    h.id = s.heading_id
ORDER BY
    s.heading_id ASC,
    s.sub_head_id ASC";

$resource = mysql_query($query);

$previous_heading = false;

// This will print the headings in a unordered list, modify if needed
echo '<ul>';
while($resource = mysql_fetch_assoc($resource)) {
    if(!$previous_heading || $previous_heading != $resource['heading']) {
        if($previous_heading) {
            echo '</ul></li>';
        }
        echo '<li>'.$resource['heading'].'<ul>';
    }
    echo '<li>'.$resource['sub_heading'].'</li>';
    $previous_heading = $resource['heading'];
}
echo '</ul></ul>';

-

  • H1
    • SH1
    • SH2
  • H2
    • SH3
    • SH5
  • H3
    • SH4
  • H4
    • SH6
+3
select * 
from heading h, subheading s 
where s.h = h.id 
order by h.title, s.title

_ ,

+3

Source: https://habr.com/ru/post/1727047/


All Articles