There are two assumptions: either I misunderstood the question or the others did.
The point: by passing 1
as second parameter to $this->db->get();
method, it sets LIMIT 1
to the query and you'll get only 1
row as result.
So, why should you need to use a loop on a single row db result?
If you use $query->result();
the result would be something like:
Array
(
[0] => stdClass Object
(
[m_name] => Foo
)
)
To get the m_name
value you can do the following:
$result = $query->result();
echo $result[0]->m_name;
By any reason, if you need a numeric array contains the value (as you did it in your loop) you can simply do it by $name[] = $result[0]->m_name;
.
And if you use $query->result_array();
the result would be something like:
Array
(
[0] => Array
(
[m_name] => Foo
)
)
To get the m_name
value you can do the following:
$result = $query->result_array();
echo $result[0]['m_name'];
But if you stop limiting the query, there are multiple rows in your query result, you can use rows1 = $query1->result_array();
instead. and array_map()
to manipulate the elements of the given array:
$rows1 = $query1->result_array();
// `$row1` will be something like this:
Array
(
[0] => Array
(
[m_name] => Foo
)
[1] => Array
(
[m_name] => Bar
)
[2] => Array
(
[m_name] => Baz
)
)
Use array_map()
to manipulate the result array:
function getName($array) {
return $array['m_name'];
}
$array = array_map("getName", $rows1);
print_r($array);
If you are using PHP v5.3+ you do the following:
$array = array_map(function($array) {
return $array['m_name'];
}, $rows1);
$name
array? – Hashem Qolami Aug 8 at 21:48row()
from ellislab.com/codeigniter/user-guide/database/results.html – machineaddict Aug 9 at 6:03