Reputation: 95
I am using a foreach
loop on an array of rows in a model file in CodeIgniter
.
What i want to do is reflect the changes i make in every row ,in the foreach
loop ,to the original array.
$unique = $this->db->get_where('list', array('item_index' => $item));
foreach ($unique->result_array() as $row)
{
$row["status"]= "Not Unique";
if($row["bid_amount"]==$amount)
{
if($count==0){ $row["status"]="Unique and Final"; }
else {$row["status"]="Unique but Not Final"; }
}
$count++;
}
return $unique;
I am adding another attribute to each row here and i want to echo this attribute corresponding to each row in a view file.
But i am getting error Undefined index: status
.
How can i possibly reflect the changes in the array to be returned.
Upvotes: 2
Views: 3373
Reputation: 7388
Assign the result_array()
to a variable, iterate over it, but change the original array and not the local one. PHP's foreach
comes in two flavours:
foreach($arr as $value)
and foreach($arr as $key => $value)
Try this:
$results = $unique->result_array();
foreach ($results as $rK => $rV){
$results[$rK]["status"]= "Not Unique";
//other stuff.
}
return $results;
Alternatively, you can pass by reference:
foreach ($results as &$result) {
$result['status'] = "Not Unique";
}
See the PHP docs on arrays. Specifically Example 10.
Upvotes: 3
Reputation: 2264
In your foreach the $row
refers to a variable that's local to the loop. Thus changing it does not affect the data in $unique
.
Upvotes: 1