【问题标题】:Create a New array from foreach in CodeIgniter在 CodeIgniter 中从 foreach 创建一个新数组
【发布时间】: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


【解决方案1】:

你有一些小问题要解决:

$new_array = array( .. ) - 这样你在每次迭代中都会覆盖数组

$new_array[] = array( .. ) - 这样您就可以在每次迭代中向数组 ($new_array) 添加新元素。

所以修改你的代码

来自

 $new_array = array(
      'task_id'           => $transfer_new['task_id'],
      'task_project_id'   => $new_project_id
   );

 $new_array[] = array(
      'task_id'           => $transfer_new['task_id'],
      'task_project_id'   => $new_project_id
   );

既然你有list_ids的列表,你可以使用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(); 

【讨论】:

  • 感谢@akshay-hedge 的回复,但该解决方案只返回数组中的一个项目(循环中的第一个任务)...
  • @OctoberEleven:你的意思是说,对于一个 task_list_id,3 个结果?为什么会有array_shift???
  • @OctoberEleven 你试过了吗,另一种带有 where_in 子句的方法,这个没有使用 foreach
  • @akshay-hedge 完美!没有任何'foreach'就可以工作/我想这会更好,性能明智吗? (顺便说一句,如果您可以将“$this>”编辑为“$this->”以供其他可能看不到的人使用)
  • @OctoberEleven:抱歉,已修正错字,感谢告知
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 2012-03-06
  • 2012-12-16
  • 2018-08-14
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
相关资源
最近更新 更多