php - Can't read data that send from controller to view by foreach
问题描述
The $results that send to the view is undefined
public function action(){
// if($this->input->post('data_action'))
// {
// $data_action = $this->input->post('data_action');
// if($data_action=="fetch_all")
// {
$api_url = "https://jsonplaceholder.typicode.com/users";
$process = curl_init($api_url); //your API url
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
curl_close($process);
$results=json_decode($return);
//finally print your API response
$this->load->view('masterPartner',$results);
//print_r($result);
// }
// }
and this is the view
<?php foreach($results as $result)
{ ?>
<tr>
<th scope="row"><?php echo $result->id ?></th>
<td></td>
<td></td>
<td></td>
<td><a class="btn btn-success " style="margin-right:5px"href="/Crudview/index.php/edit-partner" role="button">Edit</a><a class="btn btn-danger" href="/Crudview/index.php/viewApi" role="button">Delete</a>
</tr>
<?php } ?>
the first error
A PHP Error was encountered Severity: Notice
Message: Undefined variable: results
Filename: views/masterPartner.php
Line Number: 115
Second error
A PHP Error was encountered Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/masterPartner.php
Line Number: 115
解决方案
这是因为视图中不存在 $results。它期望通过数组传入 $results。
要传递它,您需要更改当前代码
从
$results=json_decode($return);
//finally print your API response
$this->load->view('masterPartner',$results);
至
$data['results']=json_decode($return);
//finally print your API response
$this->load->view('masterPartner',$data);
所以现在 $results 可以在您的视图中访问。
推荐阅读
- javascript - KnockoutJS - 我们可以为 CSS 更新调用 Observable 函数吗
- linux - 奇怪的 POSIX 信号量行为(卡在 Linux 上的 sem_wait 上)
- c++ - >= 并且 <= 没有按照我使用它们的方式工作,我在哪里搞砸了?
- python - 如何在 Pandas 中将 timedeltas 与 resample 或 groupby 相加?
- android - 如何知道Android中EditText发生了删除操作?
- machine-learning - 多类铰链损失和三重损失有什么区别?
- javascript - 调用自身的异步函数
- windows - 两个 Windows 设备之间的 webRTCConnection 失败
- coq - Coq:如何在不搞乱归纳假设的情况下正确记住依赖值?
- css - 如何让产品图片在手机版中显示?