Undefined variable in CodeIgniter View

耗尽温柔 提交于 2020-01-02 03:53:25

问题


I'm trying to print my key/value pairs of data in my CodeIgniter view. However, I'm getting the following error. What I'm I doing wrong?

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: data

Filename: views/search_page2.php

Line Number: 8

application/controller/search.php

// ...
        $this->load->library('/twitter/TwitterAPIExchange', $settings);
        $url = 'https://api.twitter.com/1.1/followers/ids.json';
        $getfield = '?username=johndoe';
        $requestMethod = 'GET';     
        $twitter = new TwitterAPIExchange($settings);

        $data['url'] = $url;
        $data['getfield'] = $getfield;
        $data['requestMethod'] = $requestMethod;        

        $this->load->view('search_page2', $data);
// ...

application/views/search_page2.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Twitter Test</title> 
</head>
<body>
<?php print_r($data); ?>

<?php foreach ($data as $key => $value): ?>
    <h2><?php echo $key . ' ' . $value . '<br />'; ?></h2>
<?php endforeach ?>
</body>
</html>

回答1:


to get the data array accessible in the view do like

    $data['url'] = $url;
    $data['getfield'] = $getfield;
    $data['requestMethod'] = $requestMethod;        

    $data['data'] = $data;
    $this->load->view('search_page2', $data);

else only the variables with names as its keys will be available in the view not the data variable we pass.

update:

this is in response to your comment to juan's answer Actually if you are trying make it working in the other way proposed.

controller code will be having no change from the code you posted.

    $data['url'] = $url;
    $data['getfield'] = $getfield;
    $data['requestMethod'] = $requestMethod;
    $this->load->view('search_page2', $data);

but in the view code you will need to just do.

 <h2>url <?PHP echo $url; ?><br /></h2>
 <h2>getfield <?PHP echo $getfield; ?><br /></h2>
 <h2>requestMethod <?PHP echo $requestMethod; ?><br /></h2>

instead of the foreach loop as your keys in $data are already available as respective named variables inside the view.




回答2:


The variables to use in your template are

 $url, $getfield, $requestMethod

$data is the container for the variables that are passed to the view and not accessible directly

If you do need $data accessible to the view, use a different wrapper object

 $container  = array();
 $container  ['url'] = $url;
 $container  ['getfield'] = $getfield;
 $container  ['requestMethod'] = $requestMethod;
 $container  ['data'] = $data;
 $this->load->view('search_page2', $container);


来源:https://stackoverflow.com/questions/16500647/undefined-variable-in-codeigniter-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!