0

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']));

    }
}
2
  • you don't need to create your own template. There are tons already done Commented Jun 20, 2011 at 15:19
  • 2
    You're not calling test2() anywhere... Commented Jun 20, 2011 at 15:24

2 Answers 2

3

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?

2
  • +1 but the wording might need to be fixed bc it took me a little to get it Commented Jun 20, 2011 at 15:29
  • So is there anyway to improve it? Commented Jun 21, 2011 at 15:06
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.