简体   繁体   English

在foreach循环ci中创建数组的索引

[英]create an index of array inside foreach loop ci

i have an array of id's through which i have to fetch data from two tables basically now let break my issue step by step 我有一个ID数组,基本上必须通过它从两个表中获取数据,现在让我们逐步解决问题

First step i have to get the id's of whom i want the data, this is the model that returns data of id's 第一步,我必须获取要获取其数据的ID,这是返回ID数据的模型

function child_get($id){
        $this->db->select("id");
        $this->db->from('generic_table');
        $this->db->where("parent",$id);
        $query = $this->db->get();
        return $query->result_array();
    }

this return an array of ids in the following format 这将返回以下格式的ID数组

Array ( [0] => Array ( [id] => 13 ) [1] => Array ( [id] => 14 ) )

i have no issue so far now i have to traverse this array and dynamically add data into array depending on the id's for this i used a foreach loop 到目前为止,我还没有问题,现在我必须遍历此数组并将此数据根据其ID动态添加到数组中,我使用了foreach循环

$arrOfIds = $data['child1'];
          foreach($arrOfIds as $row) {
             $data['child3']=array
            (
                "id" => $row["id"],
                "path" => $this->Menu->test_maindata($row["id"])
            );
          }

the model used inside foreach foreach内部使用的模型

 public function test_maindata($id)
    {
        $this->db->select("path");
        $this->db->from('main_data');
        $this->db->where("f_key",$id);
        $query = $this->db->get();
        return $query->result_array();
    }

now the first issue it overriding the every value of iteration and returning only the last value see below 现在的第一个问题是它覆盖迭代的每个值并仅返回最后一个值,请参见下文

Array ( [id] => 14 [path] => Array ( [0] => Array ( [path] => almond.jpg ) ) ) 

you can see it skipped the iteration of id 13 您可以看到它跳过了ID 13的迭代

secondly can i make this array in the following pattern 其次,我可以按照以下模式制作此数组

Array( [0] => Array( id=> 13, path=>bluebery.jpg) [1]=> Array( id=> 14, path=>almond.jpg));
just use this single query and let me know what is output this is giving

    $this->db->select("generic_table.name,main_data.path");
$this->db->from('generic_table');
$this->db->where("generic_table.id",$id);
$this->db->join("main_data","main_data.f_key = generic_table.id");
$query = $this->db->get();
return $query->result_array();

and for loop iteration 和循环迭代

$arrOfIds = $data['child1'];
          foreach($arrOfIds as $row) {
             $data['child3'][]=array
            (
                "id" => $row["id"],
                "path" => $this->Menu->test_maindata($row["id"])
            );
          }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM