doubei2340 2017-02-08 17:51
浏览 50

从具有3列(id,路径,名称)的PHP数组生成文本面包屑的最佳方法?

For one possible solution, see my second post below.

Having a PHP array storing data from a tree structure, with

  • the first column storing the id of the node,
  • the second column storing the path of the parent node as a concatenation of id values,
  • the third columns storing the name of the node,

which is the best way to generate a text path (breadcrumbs) from the path done of ids?

Example records:

id  |  path  |  name
---------------------
1   | 0       | edible

14  | 1       | fruits

53  | 1.14    | apples
54  | 1.14    | pears

122 | 1.14.53 | red apples
123 | 1.14.53 | green apples
124 | 1.14.54 | yellow pears

Input id: 122

Corresponding input path : 1.14.53

Output string: edible > fruits > apples

The idea is to achieve something like:

foreach($cats as $cat) { // for each category

    foreach(explode('.', $cat['path']) as $id) { // explode the path into chunks
      /*
       1) get the name matching the value of $id
       2) append label to breadcrumbs string
      */
      }
  // 3) output breadcrumbs for the given category
  // [4) list leaf nodes under the breadcrumbs for the current category]
}

Nota bene: The array itself is generated by this MySQL/MariaDB query:

$req = "SELECT c.id,p.path,c.name FROM `".$database['database']."`.`".$database['prefix']."productcategories` c
        LEFT OUTER JOIN `".$database['database']."`.`".$database['prefix']."prodcat_path` p
        ON c.id = p.id
        WHERE c.isparent AND (c.id=".$id." OR (p.path=".$id." OR p.path LIKE('".$id.".%') OR p.path LIKE('%.".$id.".%') OR p.path LIKE('%.".$id."'))) ORDER BY p.path ASC";
    $res = mysql_query($req) or die();

The reason for storing the path into a distinct table, with a one to one relationship for records, is that a trigger is used to compute and store the path when a new category is inserted.

  • 写回答

2条回答 默认 最新

  • douchi0471 2017-02-08 18:04
    关注

    You can also create a new function on MYSQL to get the names from the ids and use like the following:

    SELECT p.id,YOURFUNCTION(p.path),.....
    

    https://dev.mysql.com/doc/refman/5.7/en/adding-functions.html

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口