我正在处理一个URL列表,我正在尝试弄清楚它们是如何相互关联的,以便为它们提供我拥有的代码的父ID;
<?php
$stmt = $db->query(" SELECT cd.id, cd.url FROM crawl_data cd
LEFT JOIN (SELECT * FROM site WHERE crawl_stage = 2 LIMIT 1) s ON s.id = cd.`site_id`
ORDER BY cd.url DESC ");
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$url = parse_url($row['url']);
$url = (isset($url['query'])) ? $url['path'].$url['query'] : $url['path'];
$url_parts = explode("/", $url);
$page_depth = count($url_parts);
if(isset($prev_url)){
$i = 0;
while($i < count($url_parts)){
if($prev_url[$i] == $url_parts[$i]){
echo "Same - ".$prev_url[$i]." - ".$url_parts[$i]."<br>";
$i++;
}else{
echo "Different - ".$prev_url[$i]." - ".$url_parts[$i]."<br>";
$prev_url = $url_parts;
$i++;
break;
}
}
}else{
$prev_url = $url_parts;
}
}
?>
&#13;
基本上我希望它向我展示的是URL&#39; s,如下所示;
我希望这是有道理的。
答案 0 :(得分:1)
这是我的版本:
<?php
$urls = array(
array('url' => '/', 'id' => 1),
array('url' => '/article', 'id' => 2),
array('url' => '/article/123', 'id' => 3),
array('url' => '/article/1234', 'id' => 4),
array('url' => '/article/1234/123', 'id' => 5),
array('url' => '/about-us', 'id' => 6)
);
$tree = array(
);
function removeEmpty($segments) {
$clean = array();
foreach($segments as $segment) {
if($segment !== '') {
$clean[] = $segment;
}
}
return $clean;
}
function addSegments(&$tree, $segments, &$url) {
if(count($segments) === 0) {
$tree['id'] = $url['id'];
$url['leaf'] = $tree;
return;
}
$segment = array_shift($segments);
if(!array_key_exists($segment, $tree)) {
$tree[$segment] = array(
'parent' => $tree
);
}
addSegments($tree[$segment], $segments, $url);
}
for($i = 0; $i < count($urls); $i++) {
addSegments($tree, removeEmpty(explode('/', 'root' . $urls[$i]['url'])), $urls[$i]);
}
foreach($urls as $url) {
$parent = '';
if(array_key_exists('id', $url['leaf']['parent'])) {
$parent = $url['leaf']['parent']['id'];
}
echo $url['id'] . '. ' . $url['url'] . ' (' . $parent . ')' . PHP_EOL;
}
产生以下输出:
1. / ()
2. /article (1)
3. /article/123 (2)
4. /article/1234 (2)
5. /article/1234/123 (4)
6. /about-us (1)