简体   繁体   English

PHP的Foreach的单一结果?

[英]PHP Foreach for single result?

So in codeigniter I have the following in a model: 因此,在codeigniter中,我在模型中具有以下内容:

function get_product_requirements()
{
    $query = $this->db->get_where('settings', array('name' => 'product_laws'));
    return $query->result_array();
}

As you could guess this only returns one value. 如您所料,这只会返回一个值。 Right now I have a foreach to display this in the browser. 现在,我有一个foreach可以在浏览器中显示它。 It doesn't make sense to me to put a foreach for a single returned value. 对我来说,为单个返回值放一个foreach没有意义。

<?php foreach($laws as $laws){ echo $laws['content']; } ?>

Is there an alternative to how I can display this item? 除了我可以显示此项目以外,还有其他选择吗?

CodeIgniter's Active Records have a native way of returning one row: CodeIgniter的活动记录具有返回一行的本机方式:

return $query->row_array();

Then, to access your value, use this: 然后,使用以下方法来获取您的价值:

echo $laws['content']; // not inside the foreach loop, of course

Read more about different ways to fetch rows here: http://ellislab.com/codeigniter/user-guide/database/results.html 在此处阅读有关获取行的不同方式的更多信息: http : //ellislab.com/codeigniter/user-guide/database/results.html

if you sure that you get one row every time you can write your model code in this way: 如果您确定每次都能以这种方式编写模型代码,则得到一行:

function get_product_requirements()
{
    $query = $this->db->get_where('settings', array('name' => 'product_laws'));
    return $query->row();
}

and get your content with: 并通过以下方式获取您的内容:

$law = $this->model_name->get_product_requirements();
echo $law['content'];

but if you want to stay on your way you can access to your data with 但是如果您想继续前进,可以使用

$law[0]["content"];

reference: http://ellislab.com/codeigniter/user-guide/database/results.html 参考: http : //ellislab.com/codeigniter/user-guide/database/results.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM