dtuy84033 2012-03-06 04: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-06 04: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条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大