powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / как правильно сделать категории бесконечной вложенности
9 сообщений из 9, страница 1 из 1
как правильно сделать категории бесконечной вложенности
    #37888104
hemoy
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Привет всем!)

Встал вопрос, как сделать категории бесконечной вложенности,
хочу эффективно и правильно. нужна идея)

я вот думаю использовать 3 таблицы, но не очень представляю как собрать из них информацию, что бы построить дерево
...
Рейтинг: 0 / 0
как правильно сделать категории бесконечной вложенности
    #37888106
hemoy
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
еще видел способ через рекурсию, http://forum.php.su/topic.php?forum=71&topic=4385, что то мне кажется он не эффективный, хотя используется одна таблица
...
Рейтинг: 0 / 0
как правильно сделать категории бесконечной вложенности
    #37888108
Фотография ScareCrow
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
nested set например.
parent_id хранить у записи.
...
Рейтинг: 0 / 0
как правильно сделать категории бесконечной вложенности
    #37888119
hemoy
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
ScareCrow,

спс, почитал об этом способе, завтра попробую реализовать
...
Рейтинг: 0 / 0
как правильно сделать категории бесконечной вложенности
    #37888163
Фотография SmeL_md
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Заодно пару ключевых слов
FOREIGN KEY (parent) REFERENCES category (id)
и
ON DELETE CASCADE
...
Рейтинг: 0 / 0
как правильно сделать категории бесконечной вложенности
    #37888275
hemoy
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
SmeL_md,

один запрос к бд, меня уже ввел в ступор
Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
SELECT
  Level1.num as num1,
  Level1.id as id1,
  Level1.text_en as text_en1,
  Level2.num as num2,
  Level2.id as id2,
  Level2.text_en as text_en2,
  Level3.num as num3,
  Level3.id as id13,
  Level3.text_en as text_en3
FROM
 (SELECT
 categories.id,
 categories_texts.num,
 categories_texts.text_en,
 categories.nsLeftId AS nsLeftId_livel1,
 categories.nsRightId AS nsRightId_livel1,
 categories.nsLevel AS nsLevel_livel1,
 (SELECT
 categories.id
 FROM
 categories
 WHERE
 categories.nsLeftId < nsLeftId_livel1
 AND categories.nsRightId > nsRightId_livel1
 AND categories.nsLevel = nsLevel_livel1 - 1
 LIMIT
 0, 1) AS id_parent   
 FROM
 categories
 INNER JOIN categories_texts ON categories.id = categories_texts.cat_id
 WHERE
 categories.nsLevel = 1) Level1 
 LEFT JOIN
 (SELECT
 categories.id,
 categories_texts.num,
 categories_texts.text_en,
 categories.nsLeftId AS nsLeftId_livel2,
 categories.nsRightId AS nsRightId_livel2,
 categories.nsLevel AS nsLevel_livel2,
 (SELECT
 categories.id
 FROM
 categories
 WHERE
 categories.nsLeftId < nsLeftId_livel2
 AND categories.nsRightId > nsRightId_livel2
 AND categories.nsLevel = nsLevel_livel2 - 1
 LIMIT
 0, 1) AS id_parent
 FROM
 formav9utf8.categories
 INNER JOIN categories_texts ON categories.id = categories_texts.cat_id
 WHERE
 categories.nsLevel = 2) Level2 ON Level2.id_parent = Level1.id
 LEFT JOIN
 (SELECT
 categories.id,
 categories_texts.num,
 categories_texts.text_en,
 categories.nsLeftId AS nsLeftId_livel3,
 categories.nsRightId AS nsRightId_livel3,
 categories.nsLevel AS nsLevel_livel3,
 (SELECT
 categories.id
 FROM
 categories
 WHERE
 categories.nsLeftId < nsLeftId_livel3
 AND categories.nsRightId > nsRightId_livel3
 AND categories.nsLevel = nsLevel_livel3 - 1
 LIMIT
 0, 1) AS id_parent
 FROM
 categories
 INNER JOIN categories_texts ON categories.id = categories_texts.cat_id
 WHERE
 categories.nsLevel = 3) Level3 ON Level3.id_parent = Level2.id
 ORDER BY
 Level1.id,Level2.id,Level3.id ASC



http://tohait.ru/php/286

пхп пишет ошибку а запросе
...
Рейтинг: 0 / 0
как правильно сделать категории бесконечной вложенности
    #37888281
Фотография ScareCrow
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
незнаю что это но явно не то что надо.
...
Рейтинг: 0 / 0
как правильно сделать категории бесконечной вложенности
    #37888288
hemoy
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
просматривал бесплатный скрипт Shop-Script FREE 2005 WebAsyst

как там организованы категории, вполне отлично работают,

структура БД
категории:
[img=" http://djgame.ru/22222222222.png%22%5D]http://djgame.ru/22222222222.png"]
http://djgame.ru/22222222222.png

[img=" http://djgame.ru/3333333333333.png%22%5D]http://djgame.ru/3333333333333.png"]
http://djgame.ru/3333333333333.png

Построение дерева

Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
<?php
/*****************************************************************************
 *                                                                           *
 * Shop-Script FREE                                                          *
 * Copyright (c) 2005 WebAsyst LLC. All rights reserved.                     *
 *                                                                           *
 ****************************************************************************/

	// category navigation form

	//calculate a path to the category
	$path = array($categoryID);
	$curr = $categoryID;
	do
	{
		$q = db_query("SELECT parent FROM ".CATEGORIES_TABLE." WHERE categoryID='$curr'") or die (db_error());
		$row = db_fetch_row($q);
		$curr = $row ? $row[0] : 0; //get parent ID
		$path[] = $curr;

	} while ($curr);

	//now reverse $path
	$path = array_reverse($path);

	$out = processCategories(0,$path,$categoryID);

	$smarty->assign("categories_tree",$out);

?>








Код: php
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
<?php
/*****************************************************************************
 *                                                                           *
 * Shop-Script FREE                                                          *
 * Copyright (c) 2005 WebAsyst LLC. All rights reserved.                     *
 *                                                                           *
 ****************************************************************************/

	//show all products of selected category

function get_Subs($cid) //get current category's subcategories IDs (of all levels!)
{
	$q = db_query("select categoryID from ".CATEGORIES_TABLE." where categoryID<>0 and parent='$cid'") or die (db_error());
	$r = array();
	while ($row = db_fetch_row($q))
	{
		$a = get_Subs($row[0]);
		for ($i=0;$i<count($a);$i++) $r[] = $a[$i];
		$r[] = $row[0];
	}

	return $r;
}

	if (isset($categoryID) && !isset($productID) && $categoryID)
	{

		//get selected category info
		$q = db_query("SELECT categoryID, name, description, picture FROM ".CATEGORIES_TABLE." WHERE categoryID='$categoryID'") or die (db_error());
		$row = db_fetch_row($q);
		if ($row)
		{
			if (!file_exists("./products_pictures/".$row[3])) $row[3] = "";
			$smarty->assign("selected_category", $row);
		}
		else
		{
			//category not found
			header("Location: index.php");
		}

		$smarty->assign("main_content_template", "category.tpl.html");

		//calculate a path to the category
		$path = array();
		$curr = $categoryID;
		do
		{
			$q = db_query("SELECT parent, name FROM ".CATEGORIES_TABLE." WHERE categoryID='$curr'") or die (db_error());
			$row = db_fetch_row($q);
			$tmp = $curr;
			$curr = $row[0]; //get parent ID
			$row[0] = $tmp;
			$path[] = $row;

		} while ($curr);
		//now reverse $path
		$path = array_reverse($path);
		$smarty->assign("product_category_path",$path);

		//show subcategories
		$q = db_query("SELECT categoryID, name, products_count FROM ".CATEGORIES_TABLE." WHERE parent='$categoryID'") or die (db_error());
		$result = array();
		while ($row = db_fetch_row($q))
		{
			$result[] = $row;
		}
		$smarty->assign("subcategories_to_be_shown",$result);

		//show active products
		$q = db_query("SELECT count(*) FROM ".PRODUCTS_TABLE." WHERE categoryID='$categoryID' AND enabled=1") or die (db_error());
		$g_count = db_fetch_row($q);
		$g_count = $g_count[0];

		$smarty->assign("catalog_navigator", NULL);
		$smarty->assign("products_to_show", NULL);
		$smarty->assign("products_to_show_count",NULL);

		if ($g_count) // there are products in the category
		{

			if ($offset > $g_count) $offset=0;

			$q = db_query("SELECT productID FROM ".PRODUCTS_TABLE." WHERE categoryID='$categoryID' AND enabled=1 ORDER BY name") or die (db_error());

			//fetch all products
			$result = array();
			$i=0;
			while ($row = db_fetch_row($q))
			{
				if (isset($_GET["show_all"]) || ($i>=$offset && $i<$offset+CONF_PRODUCTS_PER_PAGE))
				{
					$q1 = db_query("select categoryID, name, brief_description, customers_rating, Price, picture, in_stock, thumbnail, customer_votes, big_picture, list_price, productID from ".PRODUCTS_TABLE." where productID='$row[0]'") or die (db_error());
					$row1 = db_fetch_row($q1);
					//update several product fields
					if (!file_exists("./products_pictures/".$row1[5])) $row1[5] = 0;
					if (!file_exists("./products_pictures/".$row1[7])) $row1[7] = 0;
					if (!file_exists("./products_pictures/".$row1[9])) $row1[9] = 0;
					$row1[12] = show_price($row1[4]);
					$row1[13] = show_price($row1[10]);
					$row1[14] = show_price($row1[10]-$row1[4]); //you save (value)
					if ($row1[10]) $row1[15] = ceil(((($row1[10]-$row1[4])/$row1[10])*100)); //you save (%)
					$result[] = $row1;
				}
				$i++;
			}

			//number of products to show on this page
			if (!isset($_GET["show_all"]))
			{
				$min = CONF_PRODUCTS_PER_PAGE;
				if ($min > $g_count-$offset) $min = $g_count-$offset;
			}
			else
			{
				$min = $g_count;
				$offset = "show_all";
			}

			$smarty->assign("products_to_show", $result);
			$smarty->assign("products_to_show_count", $min);

			$navigator = ""; //navigation links
			showNavigator($g_count, $offset, CONF_PRODUCTS_PER_PAGE, "index.php?categoryID=$categoryID&",$navigator);
			$smarty->assign("catalog_navigator", $navigator);

		}
		else if (CONF_SHOW_BEST_CHOICE == 1) //there are no items in the category. search for items in it's subcategories if CONF_SHOW_BEST_CHOICE is set
		{
			//are there sub categories?
			$q = db_query("SELECT count(*) FROM ".CATEGORIES_TABLE." WHERE parent='$categoryID'") or die (db_error());
			$row = db_fetch_row($q);
			if ($row[0]) //there are
			{

				//create a query for extracting products from subcategories
				$s = "SELECT productID FROM ".PRODUCTS_TABLE." WHERE enabled=1 ";
				$a = get_Subs($categoryID);
				if (count($a) > 0)
				{
					$s.= " AND (categoryID=$a[0]";
					for ($i=1;$i<count($a);$i++)
					{
						$s.=" OR categoryID=$a[$i]";
					}
					$s.= ")";
				}

				$q = db_query(str_replace("SELECT productID","SELECT count(*)",$s)) or die (db_error());
				$cnt = db_fetch_row($q); $cnt = $cnt[0];

				if ($cnt) //there are products in the subcategories
				{
					$q = db_query($s." ORDER BY customers_rating DESC") or die (db_error());
					$i=0;
					$result = array();
					while ($i<CONF_PRODUCTS_PER_PAGE && $row = db_fetch_row($q))
					{
						$q1 = db_query("select categoryID, name, brief_description, customers_rating, Price, picture, in_stock, thumbnail, customer_votes, big_picture, list_price, productID from ".PRODUCTS_TABLE." where productID=$row[0]") or die (db_error());
						$row1 = db_fetch_row($q1);
						//update several product fields
						if (!file_exists("./products_pictures/".$row1[5])) $row1[5] = 0;
						if (!file_exists("./products_pictures/".$row1[7])) $row1[7] = 0;
						if (!file_exists("./products_pictures/".$row1[9])) $row1[9] = 0;
						$row1[12] = show_price($row1[4]);
						$row1[13] = show_price($row1[10]);
						$row1[14] = show_price($row1[10]-$row1[4]); //you save (value)
						if ($row1[10]) $row1[15] = ceil(((($row1[10]-$row1[4])/$row1[10])*100)); //you save (%)
						$result[] = $row1;
					}
					$smarty->assign("products_to_show", $result);
					$smarty->assign("products_to_show_count", min($cnt, CONF_PRODUCTS_PER_PAGE));
					$smarty->assign("products_to_show_best_choice", min($cnt, CONF_PRODUCTS_PER_PAGE));
				}

			}

		}

	}
?>




Хотел, спросить, будет оптимальным использовать подобное или есть статья, где подробно будет описано с примерами, построить nested set на php
...
Рейтинг: 0 / 0
как правильно сделать категории бесконечной вложенности
    #37888464
hemoy
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
нашел тему, кто чето может дополнить?

/topic/956973
...
Рейтинг: 0 / 0
9 сообщений из 9, страница 1 из 1
Форумы / PHP, Perl, Python [игнор отключен] [закрыт для гостей] / как правильно сделать категории бесконечной вложенности
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]