dtuy84033 2012-03-05 20:35
浏览 23
已采纳

设置要在视图中使用的数组对象

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.

  • 写回答

2条回答 默认 最新

  • dongyan4157 2012-03-05 20:42
    关注

    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;
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部