【发布时间】:2017-10-02 19:56:38
【问题描述】:
我完全是 CodeIgniter 菜鸟。我正在尝试更新来自 foreach 循环的数据库中的一些项目。
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');
我新创建的数组只返回一个数组项。它应该返回 3,因为这就是数据库中具有特定 list_id 的数量。
正如您从代码中看到的那样,我正在尝试使用预设的 $project_id 批量更新特定任务,因此我需要该数组。
我正在努力寻找解决方案,但在 Stack 中找不到类似的东西,或者我根本不知道如何搜索:/
更新
在与下面的@akshay-hedge 交谈后,我意识到我试图在带有 1 个引用的“foreach”循环中获得 3 个结果。
解决方案:在“foreach”中包含另一个“foreach”,以根据需要构建我的数组。
更新代码如下:
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');
更新 2
经过更多的交谈,@akshay-hedge 提出了另一种不使用任何“foreach”的解决方案,方法是从我最初的“task_list_id”开始构建一个数组。
请检查下面接受的答案以获取解决方案。
【问题讨论】:
-
$new_array[] 将此添加到您的代码中
-
@bishop 奇怪的是,即使在 [] 之后,我在数组上也得到了 1 个结果(请在下面的 Akshay 答案中检查我的 cmets // 虽然 print_r($transfer_lists_check) 返回一个包含所有内容的数组三个结果 // 但是,我需要的是每个 task_id 找到的新数组(总共 3 个,list_id 的 x 值)——如果这一切有意义的话:/
-
@bishop 我已经用新的信息/解决方案更新了我的问题/希望这样做也可以(?)
标签: php arrays codeigniter