我有一个适用于多级类别的经典数据库表(0
表示根):
ID - Name - Father
1 News 0
2 Articles 0
3 Politics 1
4 Politics 2
5 World 3
6 World 4
我有一个这样的路径:/News/Articles/Politics
,并且上面的表数据在数组中。
我从路径上的explode()
进行/
调用开始,我尝试了几种方法,但是在所有情况下都没有用。
这是我尝试过的事情:
$cat_path_ary = explode($cfg['categories_separator'], $cat_path);
if (count($cat_path_ary) > 1) {
$catname = array_pop($cat_path_ary);
$catparent = array_pop($cat_path_ary);
$cat_id = $this->getCatIDbyName($plugin, $catname, $catparent);
} else {
$catname = $cat_path_ary[0];
foreach($this->root_cats($plugin) as $categories) {
if($categories['name'] == $catname ) {
return $categories['cid'];
}
}
}
遍历路径值并确定最终值的ID
的最佳方法是什么?
我希望从/News/Articles/Politics
返回5
。
答案 0 :(得分:1)
我很少建议对数据库进行迭代调用,这种情况没有什么不同。 由于结果集应该相对较小,因此您有能力执行全表查询并处理多维数组以实现所需的输出。
对路径中的条目进行迭代,并对符合条件的行(匹配Name
和匹配Father
)进行迭代检查。
由于每个内循环只能有一个合格行,因此break
一经发现就可获得最佳效率。 ...只要确保在更新之前先更新$id
和$parent
变量即可。
已经实施了“无合格行”检查,但它可能与您的项目无关,也可能与您的项目无关。您可以决定是否要使用此安全网。
代码:(Demo)
$resultset = [ // query just once, collect the full tree
["ID" => 1, "Name" => "News", "Father" => 0],
["ID" => 2, "Name" => "Articles", "Father" => 0],
["ID" => 3, "Name" => "Politics", "Father" => 1],
["ID" => 4, "Name" => "Politics", "Father" => 2],
["ID" => 5, "Name" => "World", "Father" => 3],
["ID" => 6, "Name" => "World", "Father" => 4]
];
$path = "/News/Politics/World";
// $path = "/Articles/The Funnies/Garfield"; // a test case that fails
// News: parent = 0, id = 1 // \
// Politics: parent = 1, id = 3 // > the intended logic
// World: parent = 3, id = 5 // /
$cfg['categories_separator'] = "/";
$breadcrumbs = explode($cfg['categories_separator'], trim($path, "/"));
// var_export($breadcrumbs); // see what is generated
$parent = 0; // default value
foreach ($breadcrumbs as $crumb) {
$id = false; // set invalid value for success check
foreach ($resultset as $row) {
if ($row["Name"] == $crumb && $parent == $row["Father"]) { // qualifying match
$id = $parent = $row["ID"]; // dual declaration
break; // break inner loop, progress to next $crumb
}
}
if (!$id) { // inner loop failed to find qualifying match
echo "Uh-oh, Broken Breadcrumb Path -- $crumb not found in $path\n";
break; // break outer loop, path is invalid
}
// echo "ID = $id for $crumb\n"; // uncomment to see progress
}
echo "ID = $id for $crumb\n"; // echo the result
输出:
ID = 5 for World