php foreach loops only once with dynamica data
I would like the output to be displayed like this:
category1 subcategory1.1 subcategory1.2
category2 subcategory2.1 subcategory2.2
Etc...
I believe it is an issue with str_replace() I'm not sure where the issue is, could someone lend a hand?
Here is the code:
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->dis开发者_如何学运维play();
One problem I can see is:
$this->file = str_replace('{'.$key.'}', $value, $this->file);
You are overwriting your $file
variable in every iteration and apart from that you are never actually setting the $file
so as far as I can see, it should be empty after running your code.
If I understood your question right, then you have to append str_replace's output to a different variable rather than the original $file:
class temp
{
var $file;
var $output;
function new_list($forum_list)
{
foreach($forum_list as $key => $value)
{
$this->output .= str_replace('{'.$key.'}', $value, $this->file);
}
return $this->output;
}
function display()
{
echo $this->output;
}
}
精彩评论