• 技术文章 >后端开发 >php教程

    这样的递归如何做?

    2016-06-13 12:59:42原创503
    这样的递归怎么做?!

    select a,
    (select b from c where ...) as d,
    e
    from f,(select j from h where ...) as i
    where ....

    我要把外层select ... from ...中,select后面的内容替换掉,而保留from后面的内容。最后变成:

    select count(*)
    from f,(select j from h where ...) as i
    where ....

    其实这相当于xml/html节点的替换,类似递归问题,想了很久也没想到解决方法。
    ------解决方案--------------------
    正则....不行

    如果你只是想得到返回的行数, 你总是可以这样做:
    select count(*) from (

    -- 你的sql --
    select a,
    (select b from c where ...) as d,
    e
    from f,(select j from h where ...) as i
    where ....

    ) tmp

    如果你非要严格做替换, 要做语法分析, 考虑到单双引号, 括号等等....
    ------解决方案--------------------
    不知道你是要写SQL指令,还是要做字符串替换
    如果是做字符串替换,可以这么写
    $s = <<< TXT
    select a,
    (select b from c where ...) as d,
    e
    from f,(select j from h where ...) as i
    where ....
    TXT;

    $ar = preg_split('/(\(?\bselect\b
    ------解决方案--------------------
    \bfrom\b)/i', $s, -1, PREG_SPLIT_NO_EMPTY
    ------解决方案--------------------
    PREG_SPLIT_DELIM_CAPTURE);

    $n = 0;
    $st = array();
    for($i=0; $i $t = strtolower($ar[$i]);
    if($t == 'select'
    ------解决方案--------------------
    $t == '(select') {
    $st[] = $i;
    }
    if($t == 'from') {
    if(count($st) == 1) break;
    array_pop($st);
    }
    }
    for($i--; $i>$st[0]+1; $i--) unset($ar[$i]);
    $ar[$st[0]+1] = " count(*)\n";
    echo join('', $ar);

    select count(*)
    from f,(select j from h where ...) as i
    where ....
    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:nbsp select from where count
    上一篇: 数据库查询结果构建多维数组解决办法 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • 求宗师帮助啊• 新手,求解决解决• 递归验证用户输入有关问题• 请教php有做成像grid样式的方法吗• php稽查并创建多级目录
    1/1

    PHP中文网