Hello, developers!

Faced such a problem:

Now displayed in this way (1 - category, 2 - article)

1) Nature 2) In the animal world

1) Nature 2) Plants

And you need to display it like this:

1) Nature 2) In the animal world 2) plants

I have a MySQL database with such data

2 tables: caregories table (has columns: id, title), goods table (has columns: id, name, category)

Here is the code I bring

<?php $connect = mysqli_connect('localhost', 'olegmowk_1', '1425pmrmsw', 'olegmowk_1'); if ($connect == false) { echo "Error connect"; } $result = mysqli_query($connect, " SELECT categories.title, goods.name FROM categories INNER JOIN goods ON categories.id = goods.category ORDER BY categories.id; "); while ( ($cat = mysqli_fetch_assoc($result)) ) { echo $cat['title']; echo " = "; echo $cat['name']; } ?> 

I hope everything is clear explained

  • In general, nothing is clear, write in a normal language, we are not Google :) - ilyaplot
  • @ilyaplot fixed - Merlin
  • @DmitriySimushev corrected - Merlin
  • You have a title (Nature), name (In the animal world, Plants). And you need to display the title, and then the names, right? - Kostiantyn Okhotnyk
  • @KonstantinOkhotnick yes - Merlin

1 answer 1

I think something like this

 while ( ($cat = mysqli_fetch_assoc($result)) ) { $categoryarticles[$cat['title']][]=$cat['name']; //Статья помещается в массив, первый уровень которого это название категории, т.е. $categoryarticles['Природа'][0]='В мире животных' } 

Then we scroll the two-dimensional array through foreach.

 foreach ($categoryarticles as $key=>$category) { echo $key; foreach ($category as $article) { echo $article; } } 

Spaces just put where necessary.

  • It works, thanks a :) - Merlin
  • That's just how to add a design for the name and title? - Merlin
  • And in what format is the output needed? - Alexey Shatrov
  • Well, for example, to change the title to the title, and to indent the name down - Merlin
  • can you implement? - Merlin