Reputation: 142
I'm a total CodeIgniter noob. I'm trying to update a few items in the DB coming from a foreach loop.
foreach($transfer_lists as $lists) {
$this->db->from('tasks');
$this->db->where('task_list_id', $lists['list_id']);
$transfer_lists_check=$this->db->get()->result_array();
$transfer_new = array_shift($transfer_lists_check);
$new_array = array(
'task_id' => $transfer_new['task_id'],
'task_project_id' => $new_project_id
);
}
$this->db->update_batch('tasks', $new_array, 'task_list_id');
My newly created array is returning one array item, only. It should return 3, as that's how many there are in the DB with that specific list_id.
As you can see from the code, I'm trying to batch_update specific Tasks with a pre-set $project_id, hence why I need the array.
I'm banging my head against the wall trying to find a solution, but couldn't yet find something similar in Stack, or simply I don't know how to search :/
UPDATE
After conversing with @akshay-hedge below, I came to realization that I was trying to get 3 results in a 'foreach' loop with 1 reference.
Solution: Including another 'foreach' within a 'foreach' to build my array as needed.
Updated code below:
foreach($transfer_lists as $lists) {
$this->db->from('tasks');
$this->db->where('task_list_id', $lists['list_id']);
$tasks_found=$this->db->get()->result_array();
// Solution to get the desired Array I was looking for
foreach($tasks_found as $tasks) {
$new_array[] = array(
'task_id' => $tasks['task_id'],
'task_project_id' => $new_project_id
);
}
}
$this->db->update_batch('tasks', $new_array, 'task_list_id');
UPDATE 2
After, some more conversing, @akshay-hedge suggested another solution without using any 'foreach', by building an array starting from 'task_list_id', which I have initially.
Please, check the accepted Answer below for the solution.
Upvotes: 2
Views: 2078
Reputation: 16997
You got something small to fix:
$new_array = array( .. )
- with this you are overwriting array in each iteration
$new_array[] = array( .. )
- with this you are adding new element to array ($new_array
) in each iteration.
So modify your code
From
$new_array = array(
'task_id' => $transfer_new['task_id'],
'task_project_id' => $new_project_id
);
TO
$new_array[] = array(
'task_id' => $transfer_new['task_id'],
'task_project_id' => $new_project_id
);
Since you got list of list_ids
you can use where_in
$new_array = $this->db->select("'$new_project_id' as task_project_id,task_id",FALSE)
->where_in('task_list_id', array_column($transfer_lists,'list_id'))
->from('tasks')
->get()
->result_array();
Upvotes: 1