PHP-嵌套mysql_fetch_array()问题使我发疯 [英] PHP - problem with nested mysql_fetch_array() driving me crazy

查看:108
本文介绍了PHP-嵌套mysql_fetch_array()问题使我发疯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MySQL查询:

SELECT title,alias,parent FROM '._prefix.'categories 
WHERE (language = \''._language.'\' || language = \'all\') 
&& status = \'published\'
ORDER BY rank ASC

结果(来自phpMyAdmin):

The Result (from phpMyAdmin):

title    |  alias   |  parent
Home     | home     |    0
Todo     | todo     |    0
Multiuser| todo_mu  |    21
Modulsys | todo_mod |    21

PHP:

while($c = mysql_fetch_array($category_result)) {
    if($c['parent'] == 0) {
        $output .= '<li><a href="'._rewrite_string.$c['alias'].'" title="'.$c['title'].'">'.$c['title'].'</a>';

        $output .= '<ul>';

        mysql_data_seek($category_result,0);

        while($d = mysql_fetch_array($category_result)) {

            $output .= '<li class="space_left"><a href="'._rewrite_string.$c['alias'].'/'.$d['alias'].'" title="'.$d['title'].'">'.$d['title'].'</a>';

            $output .= '</li>';

        }

        $output .= '</ul>';

        $output .= '</li>';
    }
}

这应该会生成这样的类别列表

This should generate a category list like that

猫1

  • subcat 1
  • subcat 2

猫2

猫3

但是它会生成类似的东西

but it generates something like that

猫1

  • 猫1
  • 猫2
  • subcat 1
  • subcat 2

使用mysql_fetch_array到另一个(嵌套)中,而不使用mysql_data_seek 一旦调用嵌套的mysql_fetch_array,将导致异常终止.它只输出cat1而已.

using the mysql_fetch_array into another (nested) without using mysql_data_seek causes an abort once the nested mysql_fetch_array was called. it only outputs cat1 and nothing more.

请提供给我解决方案,谢谢

please provide me the solution, thank you

推荐答案

$i = 0;
while($c = mysql_fetch_array($category_result)) {
    $parent = $c['parent'];
    $next_row = $i + 1;

    $not_last_row = (mysql_data_seek($category_result, $next_row)); //Move ahead to get next parent or returns false if on last row...
    $next_parent = (!$not_last_row) ? $c['parent'] : FALSE;
    mysql_data_seek($category_result, $i); //Move back to current row

    $open_list = ($parent != $prev_parent);
    $close_list = (($parent > $next_parent) || !$not_last_row); //close list if next parent is smaller number or if this is last row.

    $output .= ($open_list) ? "<ul>" : "";

    $output .= '<li>'.$c['title'].'</li>';

    $output .= ($close_list) ? '</ul>' : "";

    $prev_parent = $parent; //Set this so that on next loop, we can see if they match
    $i++;
}

有点着急,但是我认为这是您要记住的.基本上,如果前一个父级与当前父级不匹配,请打开一个列表.如果当前父级大于下一个父级,则关闭列表.

It's a bit rushed, but I think this is what you have in mind. Basically, if the previous parent does not match the current parent, open a list. If the current parent is greater than the next parent, close the list.

您可能需要添加一些内容以说明它是最后一次迭代.

You will probably need to add something to account for it being the last iteration.

这篇关于PHP-嵌套mysql_fetch_array()问题使我发疯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆