I would like to create a breadcrumb for my site that is completely data-driven.
The data is stored using MariaDB and looks like this:
parent_id | parent_name | child_id | child_name
———————————————————————————————————————————————
1 | AAA | 101 | aaa
1 | Aaa | 102 | bbb
1 | Aaa | 103 | ccc
101 | aaa | 1001 | aaaa
101 | aaa | 1002 | bbbb
102 | bbb | 1004 | cccc
102 | bbb | 1005 | dddd
2 | Bbb | 104 | ddd
If I select let say record with id='1005', I want my breadcrumb to look like 1 / 102 / 1005
Equivalent HTML is:
<div id="breadcrumb">
<ul class="breadcrumb">
<li><a href="#">1</a></li>
<li><a href="#">102</a></li>
<li>1005</li>
</ul>
</div>
Alternatively, selecting
1 / 101 / 1002
2 / 104
I found a solution for my question.
Firstly, I changed the table structure, based on the suggestions mentioned in this article . As a result, I changed my data structure to:
id | name | lft | rgt
—————————————————————————————————————————————
1 | AAA | 1 | 16
101 | aaa | 2 | 7
1001 | aaaa | 3 | 4
1002 | bbbb | 5 | 6
102 | bbb | 8 | 13
1004 | cccc | 9 | 10
1005 | dddd | 11 | 12
103 | ccc | 14 | 15
2 | BBB | 17 | 20
104 | ddd | 18 | 19
Then using php, I can easily extract the data from the table in almost the correct format with the following SQL-statement (where '$id' is a variable and depending on the user selection as mentioned earlier):
SELECT parent.id, parent.name
FROM
table AS node,
table AS parent
WHERE
node.lft BETWEEN parent.lft AND parent.rgt
AND
node.id = '$id'
ORDER BY
parent.lft;
Finally, using d3.js, I can use the following code the create the HTML:
d3.json('php/breadcrumb.php?id=' + id).get(function(error, d_breadcrumb) {
var ul = d3.select('#breadcrumb').append('ul')
.attr('class', 'breadcrumb');
ul.selectAll('li')
.data(d_breadcrumb)
.enter()
.append('li')
.append('a')
.attr('href', function(d) {
return '?id=' + d.id;
})
.text(function(d) {
return d.name;
})
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.