How to add index to foreach data from database?
In the below code I understand that foreach
$insuranceType_list
is assigning the row of data to $l
. What is the $k
for? For index
? And @
in front of any variable could make the variable into a global one? Which means I can access it anywhere throughout my application?
if(@$insuranceType_list){
foreach($insuranceType_list as $k=>$l){
$insuranceType_list[$k]->version_list = $this->mdl_quotation_template->getConditionTemplates('insurance_type_id='.$l->id);
}
}
I also don't get what is going on here:
$insuranceType_list[$k]->version_list
It would be helpful if someone can explain me.
Lets dissect:
$insuranceType_list
is an array of objects. I know this because you are accessing the values using the arrow as in $l->something
, if you had an array of arrays you would access it like this $l['something']
@
in front just meant that you are suppressing errors to that variable. It is usually used in functions of which you dont want to errors to be thrown. $k
like foreach($insuranceType_list as $l)
which means that you don't care about the index, you just want the value per every iteration. However if you plan on using the key for any reason, then you would use that $k
variable as you are currently doing. Example: Lets say you have an array is like this:
$list = [
[
'name' => 'john'
'age' => 29
],
[
'name' => 'jane'
'age' => 23
]
];
if you wanted to create strings that said "John is 29 years old". Then you would do the following:
foreach($list as $l){
echo "{$l['name']} is {$l['age']} years old";
}
however if you wanted the string to say "John is #1 on the list, and is 29 years old". Then you would do the following:
foreach($list as $k => $l){
echo "{$l['name']} is #{$k} on the list, and is {$l['age']} years old";
}
With all that said, i would shorten your code in this manner:
if (!empty($insuranceType_list)) {
foreach ($insuranceType_list as $l) {
$l->version_list = $this->mdl_quotation_template->getConditionTemplates('insurance_type_id=' . $l->id);
}
}
链接地址: http://www.djcxy.com/p/58164.html