1

模型功能

public function getUserByID($id) 
    {
        $q = $this->db->get_where('users', array('id' => $id), 1);
        $user= $q->result();
        if($user) {
        return $user;
        } else {
        return false;
        }
    }

控制器代码

$data['user'] = $this->users_model->getUserByID($id);

查看文件代码

<pre><?php print_r($user); ?></pre>

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [name] => Saleem
            [city] => Kuala Lumput
            [state] => WP
            [postal_code] => 58100
            [country] => Malaysia
            [phone] => 0123456789

        )
)

我怎样才能得到如下结果。

Array
(
            [id] => 1
            [name] => Saleem
            [city] => Kuala Lumput
            [state] => WP
            [postal_code] => 58100
            [country] => Malaysia
            [phone] => 0123456789
)

现在我需要将它用作 $user['0']->name; 我想将其用作 $user->name; 请帮我

4

5 回答 5

2

尝试

$data['user'][0] = $this->users_model->getUserByID($id);

您可以直接从控制器本身获取

或从模型中您可以通过

public function getUserByID($id) 
{
    $q = $this->db->get_where('users', array('id' => $id), 1);
    $user= $q->result();
    if(count($user) == 1) {
    return $user[0];
    } else {
    return false;
    }
}
于 2012-09-25T04:01:34.683 回答
2

在 CI 中执行此操作的正确方法是使用以下$result->row()方法:

public function getUserByID($id) 
{ 
  $q = $this->db->get_where('users', array('id' => $id), 1); 
  if( $q->num_rows() > 0 )
  {
    return $q->row();
  }

  return FALSE;
}
于 2012-09-25T05:02:47.880 回答
2

让函数getUserByID返回第一个用户

它应该解决问题

    public function getUserByID($id) 
    {
        $q = $this->db->get_where('users', array('id' => $id), 1);
        $user= $q->result();
        if(count($user) == 1) {
        return $user[0];
        } else {
        return false;
        }
    }
于 2012-09-25T04:01:08.570 回答
1

控制器

$data['user'] = $this->users_model->getUserByID($id);
foreach($data['user'] as $user)
{
$result = $user;
}
print_r($result);

会给你

Array
(
        [id] => 1
        [name] => Saleem
        [city] => Kuala Lumput
        [state] => WP
        [postal_code] => 58100
        [country] => Malaysia
        [phone] => 0123456789
 )

编辑:

或者您可以在模型中执行此操作

public function getUserByID($id) 
{
    $q = $this->db->get_where('users', array('id' => $id), 1);
    $user= $q->result();
    if(count($user) > 0) 
    {
      foreach($user as $out)
      {
       $blah = $out;
      }
    return $blah;
    } 
    else
    {
    return false;
    }
}
于 2012-09-25T04:20:43.993 回答
0

修改你的模型函数,让它像这样

public function getUserByID($id) 
{
    $q = $this->db->get_where('users', array('id' => $id), 1);
    $user= $q->result_array();
    if($user) {
    return $user;
    } else {
    return false;
    }
}
于 2012-09-25T15:40:02.473 回答