0

我对以下代码有一个非常奇怪的问题。出于某种原因,除非将其放在 if 和 else...if 语句之外,否则我无法让 $id1 或 $id2 保存值。变量根本不会注册。有人看到我做错了吗?我很茫然。。

public function addCommentToStartpageWall() {
        $userid = $this->session->userdata("userid");
        $postingUserId = $this->input->post("postinguserid");

        $query = $this->db->query("SELECT * FROM churchmembers");
        $row = $query->row();
        foreach ($query->result() as $row) {
            if ($postingUserId == $row->cMuserId) { // check to see what church the posting user is a member of
                $id1 = $row->cMchurchId; // if posting user is a member of a church set it to var id1
            } if ($userid == $row->cMuserId) { // check to see what church myuserid is a member of
                $id2 = $row->cMchurchId; // if myuserid is a member of a church set it to var2
            } if ($id1 == $id2) { // if posting user and myuserid are a member of the same church process the following
                echo json_encode(array('id1' => $id1, 'isMembershipSame' => true));
            } elseif ($id1 != $id2) { // if posting user and myuserid are not a member of the same user process the following
                echo json_encode(array('id1' => $id1, 'isMembershipSame' => false));
            }
        }
    }
4

2 回答 2

1

看来我也错了,上面的答案是正确的。

但是,我建议在每个循环中重置 $id1 和 $id2 变量,以防止它们保留上一次迭代的值:

foreach ... 
{
    $id1 = "";
    $id2 = "";

    // ...
}
于 2012-08-24T20:17:16.903 回答
0

您必须在循环之外声明/启动这些变量。我相信这是范围的问题——一旦循环结束,这些变量就会被丢弃。

编辑:我错了 - 我猜这是你的 if/else 没有正确评估。

于 2012-08-24T20:15:49.417 回答