1

为什么我会收到以下错误

遇到 PHP 错误 严重性:警告消息:未定义变量:json 文件名:views/search_page.php 行号:8

遇到 PHP 错误严重性:警告消息:尝试获取非对象文件名的属性:views/search_page.php 行号:8

遇到 PHP 错误 严重性:警告消息:为 foreach() 提供的参数无效 文件名:views/search_page.php 行号:8

用这个代码?

搜索.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Search extends CI_Controller {

    public function index()
    {

        $json = json_decode(file_get_contents('http://search.twitter.com/search.json?q=to%3astackexchange'));

        $this->load->view('search_page', $json);
    }
}

/* End of file search.php */
/* Location: ./application/controllers/search.php */

search_page.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Twitter Test</title> 
</head>
<body>
<?php foreach ($json->results as $result): ?>
    <h2><?php echo $result->from_user; ?></h2>
<?php endforeach ?>
</body>
</html>
4

1 回答 1

4

您需要将传入的变量 ( $json) 分配给一个名称 ("json")

$this->load->view('search_page', array('json' => $json));

也许是一个更清楚的例子:

$this->load->view('search_page', array('myNeatObject' => $json));

// ...then, in your view, you could

<p>This is the JSON: <?php echo print_r($myNeatObject, true) ?></p>

这就是在视图中命名变量以供访问的方式。

于 2013-04-30T21:46:56.983 回答