从stdClass对象中删除stdClass对象和count(post_id)([count(post_id)] => 1)只需要结果1

时间:2017-03-20 06:23:11

标签: php mysql codeigniter

我的mysql查询是:

$query=('SELECT count(post_id)  FROM comments where   post_id='.$row['post_id']);
 $usercomments = $this->db->query($query);
 foreach ($usercomments->result() as $comments)

我得到的输出:

stdClass Object ( [count(post_id)] => 1 )

如何获得计数值1?怎么打印?

4 个答案:

答案 0 :(得分:1)

将您的查询更改为:

SELECT count(post_id)  FROM comments where   post_id='.$row['post_id'];

SELECT count(post_id) as post_count  FROM comments where   post_id='.$row['post_id'];
//here post_count is an ALIAS for the count(post_id)

然后得到它的值:

$comments->post_count;

答案 1 :(得分:0)

你可以这样做:

$comments = (array)$comments;
$count = reset($comments);

var_dump($count); // => 1

注意:reset返回数组的第一个值。

答案 2 :(得分:0)

您可以使用获取字符串来获取包含PHP字符的值:

$usercomments->{"count(post_id)"};

答案 3 :(得分:0)

您可以使用别名

$query=('SELECT count(post_id) as numberPost  FROM comments where   post_id='.$row['post_id']);
$usercomments = $this->db->query($query);
 foreach ($usercomments->result() as $comments)

所以你可以像这样访问对象

comments->numberPost