php array in another function
Ok now its weird but when i print the array in the test1 function its prints all the arrays but when it display it from the test2 function its displays only the last records can anyone tell me where i am wrong?
class template{
private $block = array();
private $page;
public function test1($data){
foreach($data as $k => $v){
$this->block[$k] = $v;
}
print_r ($this->block);
}
public function test2(){
开发者_开发百科 print_r ($this->block);
}
}
$template = new template();
while($row1 = mysql_fetch_assoc($bbcat)){
$template->test1(array("TIT" => $row1['title']));
while($row2 = mysql_fetch_assoc($bbscat)){
$template->test1(array("FTIT" => $row2['title']));
}
}
It's because the foreach loop is looping and setting $this->block
. So once it's done the last iteration $this->block
is now set to the data in the last loop.
CLARIFICATION
Every loop we do in the foreach loop is setting $this->block
to some new data. Once the last iteration of the loop has finished we are given the data which was outputted in the final loop.
Does that make more sense?
The reason you only see the last record is because you overwrite all previous records, as you do this in your while
-loop:
$template->test1(array("TIT" => $row1['title']));
Then inside test1()
you do a rather weird statement:
public function test1($data){
foreach($data as $k => $v){
$this->block[$k] = $v;
}
print_r ($this->block);
}
You do foreach($data as $k => $v)
, which is not neccesary, since there is only ONE value in the array (one key value pair). Nonetheless, you assing $this->block[$k] = $v;
and $k
is the same everytime (TIT
and FTIT
), so you overwrite all previous set values each time you call test1()
.
If you then call test2()
, which has no 'set' capabilities, but rather only displays $this->block
, you only get the last value for TIT
and FTIT
.
精彩评论