PHP foreach值在数组中

时间:2014-02-06 05:09:32

标签: php mysql arrays foreach

我正在制作一个Staff Online部分供会员查看天气,任何工作人员都在游戏中帮助他们。我开始使用Staff Members帐户ID的数组来解决这个问题。它看起来像这样:

$this->view->staffAdmins = array(64, 80, 96);

然后我使用foreach语句获取每个帐户的以下详细信息:

  • 他们是否已登录?
  • 如果是,请使用数组中的ID并从users
  • 获取更多信息

我的foreach语句如下所示:

foreach ($this->view->staffAdmins as $query) {
    //Are they logged in?
    $sql = "SELECT * FROM point WHERE uid = :ID AND zoneid > -1";
    $arr = array(":ID" => $query);
    $this->view->result = $this->database->DBCtr($sql, $arr);
    //Get their details!
    $sql = "SELECT * FROM users WHERE ID = :ID";
    $arr = array(":ID" => $query);
    $this->view->staffmem = $this->database->DBQry($sql, $arr);
    $this->view->name = $this->view->staffmem[0]['name'];
    $this->view->truename = $this->view->staffmem[0]['truename'];
    if ($this->view->result == 1){
        echo $this->view->truename;
    }
}

返回以下输出:

Hulu is Online
Cookiez is Online

这正是我需要的,但它会在页面的最顶部输出,这不是我需要的。当我尝试将echo $this->truename;放在它呈现的实际页面上的正确位置时,输出为

Cookiez is Online

它只获得阵列中第二名工作人员的ID (80),而我们都是同时登录的。

此外,这是我用attempt获取与工作foreach语句相同的输出的代码。这也是该类渲染的页面。

foreach ($this->staffAdmins as $staff){
    if ($this->result == 1){
        foreach ($this->staffmem as $logged){
        echo $logged['truename'];
        }
    }
}

1 个答案:

答案 0 :(得分:1)

你可以为这样的登录用户制作一个数组

$arr_logged_users = array(); // array to store logged in users

foreach ($this->view->staffAdmins as $query) {
    //Are they logged in?
    $sql = "SELECT * FROM point WHERE uid = :ID AND zoneid > -1";
    $arr = array(":ID" => $query);
    $this->view->result = $this->database->DBCtr($sql, $arr);
    //Get their details!
    $sql = "SELECT * FROM users WHERE ID = :ID";
    $arr = array(":ID" => $query);
    $this->view->staffmem = $this->database->DBQry($sql, $arr);
    $this->view->name = $this->view->staffmem[0]['name'];
    $this->view->truename = $this->view->staffmem[0]['truename'];
    if ($this->view->result == 1){
        $arr_logged_users [] = $this->view->truename; // assign here to array
    }
}

现在你可以在任何你想要的地方使用$arr_logged_users

foreach($arr_logged_users as $val)
{
    echo $val;
}