问题描述
|
我希望输出显示如下:
类别1
子类别1.1
子类别1.2
类别2
子类别2.1
子类别2.2
等等...
我相信这是str_replace()的问题
我不确定问题出在哪里,有人可以帮忙吗?
这是代码:
class temp
{
var $file;
function get_file($temp){
$this->file = get_file_contents($temp)
return $this->file;
}
function new_list($forum_list)
{
foreach($forum_list as $key => $value)
{
$this->file = str_replace(\'{\'.$key.\'}\',$value,$this->file);
}
return $this->file;
}
function display()
{
echo $this->file;
}
}
$temp = new temp();
$temp->get_file(\'file.html\');
MysqL_select_db($database_config,$config);
$query_cat = \"SELECT * FROM category ORDER BY dsp ASC\";
$cat = MysqL_query($query_cat,$config) or die(MysqL_error());
while ($row_cat = MysqL_fetch_array($cat)){
$temp->new_list(array(
\'CAT_TITLE\' => $row_cat[\'title\'],\'CAT_DESCRIPTION\' => $row_cat[\'description\']));
$cid = $row_cat[\'id\'];
MysqL_select_db($database_config,$config);
$query_cat = \"SELECT * FROM subcategory WHERE cid={$cid}\";
$subcat = MysqL_query($query_subcat,$config) or die(MysqL_error());
while ($row_subcat = MysqL_fetch_array($subcat)){
$temp->new_list(array(
\'SUBCAT_TITLE\' => $row_subcat[\'title\'],\'SUBCAT_DESCRIPTION\' => $row_subcat[\'description\']));
}
}
$temp->display();
解决方法
我可以看到的一个问题是:
$this->file = str_replace(\'{\'.$key.\'}\',$value,$this->file);
您将在每次迭代中覆盖$file
变量,除此之外,您实际上从未设置过$file
,据我所知,运行代码后该变量应为空。
,如果我正确理解您的问题,那么您必须将str_replace \的输出附加到其他变量,而不是原始的$ file:
class temp
{
var $file;
var $output;
function new_list($forum_list)
{
foreach($forum_list as $key => $value)
{
$this->output .= str_replace(\'{\'.$key.\'}\',$this->file);
}
return $this->output;
}
function display()
{
echo $this->output;
}
}