2

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.

1
  • I do not want to copy all the attributes of $unique in a fresh 2-d array ,for each row, and add another attribute status to it. Commented Sep 9, 2012 at 23:13

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I understand that now but i cannot find a way to reflect the changes to every row in $unique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.