4

我认为我有这个错误,无法找出问题所在。

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: c

Filename: views/commentsList.php

Line Number: 10 

这是我的查看代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>

<div id="commentsByParentId">
   <?foreach($comments as $c):?>
        <?=$c['comment']?>
    <?endforeach?>

</div>
</body>
</html>

$comments是来自控制器的数组。$c是循环变量,所以我不明白为什么它会捕获undef var error

UPD:这是我的控制器代码

public function viewCommentsListByParentId($parentid) {
    $data = array();
    $data = $this->em->getRepository('Entities\Comment')->findBy(array('parentid' => $parentid));
    $comments = array();
    for ($i=0; $i<count($data); $i++){
        $comments[$i]['comment'] = $data[$i]->getComment();
    }
    $this->load->view('commentsList', $comments);
}
4

5 回答 5

1

您的服务器是否允许<?标签。有些配置没有,它们会将它们变成常规的 html 注释。试试看<?php foreach($comments as $c): ?>是否能解决问题。

编辑:

现在我们修复了这个错误,它不知道 $comments 是什么。那是因为在您的控制器中,您将其定义为 $commentsList:

所以你需要<?php foreach($commentsList as $c): ?>

注意:您仍然不能使用<?标签,因为这首先是问题所在。

第二次编辑:

我查阅了 CodeIgnitor 的文档,它说您必须在$this->load->view('view_name', $data);其中包含 data 是一个值数组,其中 key 是视图中使用的变量名,而 value 是该键的值。

所以试试这个:$this->load->view('view-name', array('comments' => $comments));

然后在视图中返回<?php foreach($comments as $c): ?>

有关详细信息,请参阅

于 2013-02-28T08:24:17.043 回答
0

查看您的控制器代码后:您需要在关联数组中传递 $comments 以查看:

$data['comments'] = $comments; 
$this->load->view('commentsList', $data);
于 2013-02-28T08:19:46.327 回答
0

尝试这个 :

<?php 
foreach($comments as $c){
    echo $c['comment'];
}
?>
于 2013-02-28T08:35:43.893 回答
0

大家,谢谢。我以这种方式解决了这个问题。我将控制器更改为此。传递控制器对象数组似乎比传递数组数组更好。

public function viewCommentsListByParentId($parentid) {
    $data = array();
    $data['comments'] = $this->em->getRepository('Entities\Comment')->findBy(array('parentid' => $parentid));
    $this->load->view('commentsList', $data);
}

并改变了我的看法

   <?php foreach($comments as $c):?>
        <?=$c->getComment()?><br>
    <?php endforeach?>
于 2013-02-28T10:28:02.080 回答
0

你到那里的奇怪错误。为什么在 foreach 循环中没有 HTML 时使用简写 PHP 标记?还是生产代码不同?

您可以使用以下代码(解决方法)使您的代码工作:

<?php
    foreach($comments as $key=>$c) {
        if(isset($c) && isset($c['comment'])) {
            echo $c['comment'];
        } else {
            echo 'Error at index ' . $key;
        }
    }
?>

请报告您返回的手动错误。

于 2013-02-28T09:18:59.493 回答