When a creating an array and get value of an certain column from the database, I have a array format whether is this the same or not?
$result['user_name']
and $result[0]->user_name
At this point, it's just 'regular' PHP. As @RashFlash pointed out, many times in Codeigniter, an array or object is created from the database result. The documentation for that is here: https://www.codeigniter.com/userguide3/database/results.html
So your first $result['user_name']
is just referencing an array where the key is 'user_name'
and the latter is referencing a property of the first object in the array.
Often the processing/display of database results goes something like this object based example (taken from the above documentation).
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
or
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
When a creating an array and get value of an certain column from the database, i have a array format whether is this the same or not?
$result['user_name'] and $result[0]->user_name
In codeigniter
$query->result() ; // returns object
$query->result_array(); // returns array
$query->row(); // returns object
$query->row_array(); // returns array
In PHP (very basic)
To access array elements you have to use either []
or which you don't see that much, but which you can also use is {}
.
echo $array[0];
echo $array{0};
To access an object property you have to use ->
.
echo $object->property;
If you have an object in another object you just have to use multiple ->
to get to your object property.
echo $objectA->objectB->property;
Accessing Array:
$ php -r '$a=array("s"=>123); echo $a{"s"}.PHP_EOL; echo $a["s"].PHP_EOL;'
123
123
Accessing Object:
php -r '$a=$b=new stdClass; $a->s="test"; $b->t="second"; $a->r=$b; echo $a->s.PHP_EOL; echo $a->r->t.PHP_EOL;'
test
second
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.