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 に答える