为什么子数组的元素不能显示?
可以肯定的不是编码问题。
曾用英文做过测试,同样子数组元素只显示第一个字母。
我的模板(test.php):
CODE:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<title>巢状循环测试</title>
</head>
<body>
<table width="250" border="0" align="center" cellpadding="3" cellspacing="0">
<{ section name=sec1 loop=$forum }>
<tr>
<td colspan="2"><{ $forum[sec1].category_name }></td></tr>
<{ section name=sec2 loop=$forum[sec1].topic }>
<tr>
<td width="25"></td>
<td width="224"><{ $forum[sec1].topic[sec2].topic_name }></td></tr>
<{ /section }>
<{ /section }>
</table>
</body>
</html>php文件(db_conn.php):
CODE:
<?php
require "main.php";
// 先建立第一层数组
$category_arr = array();
$db = new mysqli('localhost','hyweb','hypw','smarty_test');
$sq = "set names gb2312";
$db->query($sq);
$sq1 = "select * from category";
$rs1 = $db->query($sq1);
if(!$rs1) die($db->error());
// 抓取第一层循环的资料
while($item_category = $rs1->fetch_assoc()){
// 建立第二层数组
$topic_arr = array();
$sq2 = "select topic_name from topic where category_id=".$item_category['category_id'];
$db->query($sq);
$rs2 = $db->query($sq2);
if(!$rs2) die($db->error());
while($item_topic = $rs2->fetch_assoc()){
array_push($topic_arr,$item_topic['topic_name']);
//echo $item_topic['topic_name'];
}
// 把第二层数组指定为第一层数组所抓取的数据中的一员
$item_category['topic'] = $topic_arr;
// 把第一层数据压入第一层数组
array_push($category_arr,$item_category);
}
$tpl->assign("forum",$category_arr);
$tpl->display("test3.htm");
// 使用foreach遍历$category_arr中的topic元素(是数组) 测试成功。
/*
foreach($category_arr as $sub_arr){
foreach($sub_arr as $key=>$value){
if(is_array($value)){
foreach($value as $i=>$sub_va)
echo $i.'->'.$sub_va.'<br />';
}else{
echo $key.'->'.$value.'<br />';
}
}
}
*/
?>首先,我确定从数据库中读出数据,并且生成数组,内容如下:
category_id->1
category_name->公告板
topic 0->站务公告
category_id->2
category_name->文学专区
topic 0->好书欣赏
1->奇文共读
category_id->3
category_name->计算机专区
topic 0->软件
1->硬件
从浏览器打开db_conn.php 结果如下:
公告板
?
文学专区
?
?
计算机专区
?
?
为什么子数组的元素不能显示?
可以肯定的不是编码问题。
曾用英文做过测试,同样子数组元素只显示第一个字母。
2008-07-05 编辑
我又写了一个php文件,不从mysql中抓取数据。内容如下:
CODE:
<?php
require "main.php";
$forum = array(array("category_id"=>1,
"category_name"=>"公告区",
"topic"=>array(array("topic_id"=>1,"topic_name"=>"站务公告"))),
array("category_id"=>2, "category_name"=>"文学专区",
"topic"=>array(array("topic_id"=>2,"topic_name"=>"好书欣赏"),
array("topic_id"=>3,"topic_name"=>"奇文共读"))),
array("category_id"=>3,"category_name"=>"计算机专区",
"topic"=>array(array("topic_id"=>4,"topic_name"=>"硬件外围"),
array("topic_id"=>"5","topic_name"=>"软件讨论"))));
$tpl->assign("forum",$forum);
$tpl->display("test3.htm");
?>显示结果完全正常。如下
公告区
站务公告
文学专区
好书欣赏
奇文共读
计算机专区
硬件外围
软件讨论
无奈+郁闷ing
[ 本帖最后由 hyeme 于 2008-7-5 18:14 编辑 ]

我也来说两句 查看全部评论 相关评论