php - PHP 中的 MySql 查询问题

标签 php mysql sql

我有一个数据库表category_path 它处于父子关系中 它看起来像这样

-----------------------------
 id   |    parent_id
------------------------------
  1   |   NULL        
  2   |   1        
  3   |   2        
  4   |   1        
  5   |   3        
  6   |   2        

使用这个表我想创建一个新表 会给我这样的输出。 下表显示了每个 id 通过遍历其父级从父级 0 到该 id 的距离。

----------------------------------
   #  |id     | parent_id | distance    
----------------------------------
   1  |  1    |   1       |   0  
   2  |  1    |   2       |   1  
   3  |  1    |   3       |   2  
   4  |  1    |   4       |   1  
   5  |  1    |   5       |   3  
   6  |  1    |   6       |   2
   7  |  2    |   2       |   0
   8  |  2    |   3       |   1
   9  |  2    |   5       |   2
   10 |  2    |   6       |   1
   11 |  3    |   3       |   0
   12 |  3    |   5       |   1
   13 |  4    |   4       |   0
   14 |  5    |   5       |   0
   15 |  6    |   6       |   0

如何通过数据库查询或编码获取?

最佳答案

最后,在这里度过整个晚上是您的解决方案:

function findValue($key,$src){

    return $src[$key];
}    

function inPatentList($val, $patent_list){

    return (in_array($val, $patent_list)) ? true : false;
}

function findFullTraverse($id, $src,&$str){
    if(0 != ($value = findValue($id, $src))){
        if($str==''){
            $str .= $value;
        }else{
            $str .= '_'.$value;
        }
        findFullTraverse($value,$src,$str);
    }
}
$id_parent = array(
    '1' => '0',
    '2' => '1',
    '3' => '2',
    '4' => '1',
    '5' => '3',
    '6' => '2',
);
$parent = array_values($id_parent);
$ids = array_keys($id_parent);

$depth = array();
$keys_for_value = array();
$id_parent = array_reverse($id_parent, true);
foreach($id_parent as $key => $val){

    $depth[] = $key.'_'.$key.'_0';
    if(inPatentList($key, $parent)){
        $keys_for_value = array_keys($id_parent, $key);
        $depth_found[$key] = $keys_for_value;
        foreach ($depth_found[$key] as $value){
            $str = '';
            findFullTraverse($value, $id_parent,$str);
            //echo $value.'=>'.$str.'<br/>';
            $traverse_array = explode('_', $str);
            for($i=0;$i<sizeof($traverse_array);$i++){
                $has_depth = $i + 1;
                $depth[]=$traverse_array[$i].'_'.$value.'_'.$has_depth;
            }
        }
    }
}

sort($depth);
echo '<pre>';
print_r($depth);
echo '<pre>';

希望这能奏效!!!

关于php - PHP 中的 MySql 查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10531390/

相关文章:

mysql - 如何修复 ERROR 1064 (42000) 语法错误?

php - 从 PHP 表中选择行的子集

mysql - Moodle 从数据库 : How to SELECT the first record which meets the WHERE clause? TOP 读取数据不起作用

php - Zend Framework 应用程序中的 "session has already been started...."异常

php - foreach 中的数据用于更新查询

php - 获取与用户相关的所有行

sql - 获取连接的逆?

php - 使用 PHP PDO 查询选择 2 列

PHP Array Speed : Is 10, 000 个元素太多无法及时访问关联数组?

php - WooCommerce:显示类别名称