0

In cakephp, I retrieve data from mysql and assign them to an array but i am unable to reuse each element of it in the view.

In the controller i call the model to query data from the database, which have the following format

Array ([0]=>Array([user]=>Array([something]=>somevalue [somethingelse]=>someotherValue))
   [1]=>Array([user]=>Array([something]=>somevalue [somethingelse]=>someotherValue))
    .......)

and I initilize my ready-to-pass-to-view array as follows, $result is the array obtained from database.

$i=0;
foreach($result as $row)
{
   $exportDt[$i]['something']=$row['user'][something];
   $exportDt[$i]['somethingelse']=$row['user'][somethingelse];
}

this->set($exportDt);

How can i reuse this exportDt array in the view ? I am thinking that setting is allowed for only one dim array only.

0

2 Answers 2

1

It appears you just need to use the correct syntax for setting the variable (ie passing the variable from the controller to the view):

//controller
$this->set('exportDt', $exportDt);

//view
print_r($exportDt);

The first parameter for $this->set() is the name of the variable that you want accessible from the view. The second is the data to put into that variable.

So, for example, you can even use other names:

//controller
$this->set('myVar', $exportDt);

//view
print_r($myVar);

Another common practice is to use PHP's compact. It looks for a variable by the name of the string(s), and creates an array with the name=>value

...compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract().

Example:

//controller
$this->set(compact('exportDt');

//view
$print_r($exportDt);

More commonly, it's used with multiple variables:

//controller
$var1 = 'whatever';
$myVar = 'something else';
$anotherVar = true;
$this->set(compact('var1', 'myVar', 'anotherVar'));

//view
echo $var1. ' ' . $anotherVar . ' ' . $myVar;
Sign up to request clarification or add additional context in comments.

Comments

1

controller part

$this->set('exportDt', $exportDt);

view part

you can directly access $exportDt as array in .ctp file

Thanks

Comments

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.