简体   繁体   中英

PHP Foreach for single result?

So in codeigniter I have the following in a model:

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. It doesn't make sense to me to put a foreach for a single returned value.

<?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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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