Home >Backend Development >PHP Tutorial >哪位看下这个循环嵌套数组有误吗?

哪位看下这个循环嵌套数组有误吗?

WBOY
WBOYOriginal
2016-06-23 13:53:55954browse

function get_number_list($cat_id){ $sql=$GLOBALS['db']->query("select * from ".$GLOBALS['db']->table('dept_category')." order by sort"); while($row=$GLOBALS['db']->fetch_array($sql)){   if($row){   $result=$GLOBALS['db']->query("select * from ".$GLOBALS['db']->table('number')." where dept=".$row['cat_id']." and cat_id='$cat_id' order by sort");	 while($rows=$GLOBALS['db']->fetch_array($result)){	    if($rows){	   $number_show[] = array(	          'id' => $rows['id'],			  'title' => $rows['title'],			  'user' => $rows['username']	   );	  }	 }        $cat_name[]=array(	      'sort' => $row['sort'],	      'cat_name' => $row['cat_name'],		  'topid' => $number_show	 );     }   }   return $cat_name; }

这个是源代码,这是截图:
这个是静态页面代码:
<table width="99%" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">                             {foreach from=$dept_list name=dept_list item=dept}							  <tr bgcolor="#FFFFFF">                                <td height="25" colspan="2" class="bumen"> {$dept.cat_name}</td>                                </tr>							{foreach from=$dept.topid item=number}                              <tr bgcolor="#FFFFFF">                                <td width="46%" height="25" align="center">{$number.user}</td>                                <td width="54%" align="center">{$number.title}</td>                              </tr>							    {/foreach}							  {/foreach}                            </table>


回复讨论(解决方案)

因为你number_show没有清空,第一个记录获取到的一直在,所以后面就都有了。

另外

while($row=$GLOBALS['db']->fetch_array($sql)){   if($row){

$row已经是在While的条件里了,没必要再加个if判断了,因为如果这个If是假的话,根本就进不了while了。

因为你number_show没有清空,第一个记录获取到的一直在,所以后面就都有了。


那我该怎么做?

function get_number_list($cat_id){ $sql=$GLOBALS['db']->query("select * from ".$GLOBALS['db']->table('dept_category')." order by sort"); while($row=$GLOBALS['db']->fetch_array($sql)){   if($row){   $result=$GLOBALS['db']->query("select * from ".$GLOBALS['db']->table('number')." where dept=".$row['cat_id']." and cat_id='$cat_id' order by sort");     while($rows=$GLOBALS['db']->fetch_array($result)){        if($rows){       $number_show[] = array(              'id' => $rows['id'],              'title' => $rows['title'],              'user' => $rows['username']       );      }     }        $cat_name[]=array(          'sort' => $row['sort'],          'cat_name' => $row['cat_name'],          'topid' => $number_show     );    unset($number_show);     }   }   return $cat_name;   unset($cat_name); }
利用unset对数组进行清空。

谢谢两位的回答

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn