Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 查询代码点火器中未定义的id_Php_Codeigniter - Fatal编程技术网

Php 查询代码点火器中未定义的id

Php 查询代码点火器中未定义的id,php,codeigniter,Php,Codeigniter,我的应用程序中有一个模型: public function get_news() { .... $this->load->database(); $top_news = $this->db->query("SELECT * FROM News "); if ($top_news->num_rows()) { $top_news = $top_news->r

我的应用程序中有一个模型:

public function get_news() 
{
    ....
        $this->load->database();


        $top_news = $this->db->query("SELECT * FROM News ");

        if ($top_news->num_rows()) 
        {
            $top_news = $top_news->result();
            $top_news['AuthorInfo'] = $this->get_author($top_news['Userid']);
            $this->cache->save('home.top_news', $top_news, 600);
        } 
        else 
        {
            $this->cache->save('home.top_news', NULL, 600);
        }
    }

    return $top_news;
}
public function get_author($author_id)
{
    $this->load->database();
    $author = $this->db->query("SELECT * FROM AdminUsers WHERE id=? LIMIT 1", array($author_id));
    if ($author->num_rows())
    {
        $author = $author->row_array(); 
    }
    else 
    {
        $author = NULL;
    }

    return $author;
}
我得到了一个错误:

Message: Undefined index: Userid  
但此字段存在于我的数据库的表News中。
我不明白我的问题出在哪里。
请帮帮我,伙计们

我写了var_dump我得到了

Array
(
  [0]=>stdClass object
    (
       [id]=>56
       [Userid]=>4
       ...

通过此查询,您将获得一个结果集(0,1或更多行),而不是一行:

    $top_news = $this->db->query("SELECT * FROM News ");
您需要循环查看结果

foreach ($top_news->result_array() as $row)
{
   $row['AuthorInfo'] = $this->get_author($row['Userid']);
   $this->cache->save('home.top_news', $row, 600);
}
如果您确定只接收一行,或者只想选择第一行,则可以使用以下选项:

 $row = $top_news->row_array(); 
 $row['AuthorInfo'] = $this->get_author($row['Userid']);
 $this->cache->save('home.top_news', $row, 600);

$top\u news
是一个对象,而不是数组,如果要获取第一个用户id,则需要获取位于
$top\u news[0]
中的用户id

所以改变

$this->get_author($top_news['Userid')


$this->get\u author($top\u news[0]->Userid)

您应该首先正确获取所有新闻,然后循环设置
AuthorInfo
并保存缓存
结果

您的查询应如下所示:

$query = $this->db->query("SELECT * FROM News");

$top_news = $query->result_array();

foreach($top_news as &$row)
{
     $row['AuthorInfo'] = $this->get_author($row['Userid']);
}

$this->cache->save('home.top_news', $top_news, 600);

我同意他可能需要创建一个循环,但是考虑到函数
get\u author
自己进行db查询,他应该真正生成一个新的结果数组,并执行单个查询,而不是在foreach循环中运行这些查询。我认为,尝试获取非objectSame注释的属性时出现了一个错误,正如下面Bora的答案所示。