变量不会在foreach循环中保存值

时间:2012-08-24 20:11:27

标签: php codeigniter

我对以下代码有一个非常奇怪的问题。出于某种原因,除非将其放在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));
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

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

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

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

    // ...
}

答案 1 :(得分:0)

您必须在循环之外声明/启动这些变量。我认为这是范围的问题 - 一旦循环结束,那些变量就会被破坏。

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