dongtiran7769 2018-07-16 18:02
浏览 81
已采纳

php通过id将多个记录输入到对象中以便稍后输出

This is a simple batch of code, I have tried things such as $Projects = (Object) $array and others that involve converting arrays to objects, and objects to arrays. My issue always stays the same where when the $_GET is populated all records from the PE table are sent into the ProjectEmployees variable. From there, I use a foreach to go through each one and take each of the Project IDs and take the corresponding project and add it to the Projects object. This object is then sent to a form where all the data is read out and displayed.

My issue is that within the foreach loop the $Projects object gets overwritten and only ever outputs 1 record, even though I know there should be 2, it is also the second record so I know it is overwriting not just skipping. I know it is reaching that point as the find function is a select * where the EmployeeID = ID which I have tested within the database itself so I know it should work.

public function list() {
    if (isset($_GET['employee'])){
        $ProjectEmployees = $this->ProjectEmployeesTable->find('EmployeeID', $_GET['employee']);

        foreach($ProjectEmployees as $ProjectEmploy){
            $Projects = $this->projectsTable->find('ProjectID', $ProjectEmploy->ProjectID);
        }
}

So my question is whether there is any way to correctly iterate the records I want from the ProjectsTable ,according to the project IDs within the ProjectEmployees variable, into Projects.

  • 写回答

2条回答 默认 最新

  • doushuo1989 2018-07-16 18:51
    关注
    1. You need to store all project in array like: $Projects=array();
    2. In foreach loop You need to push all project in that
      $Projects array.
    3. Then you need to return this array like: return $Projects;.
    4. Getting the result you need to call that method.

    Calling this method like this:

    $obj = new YourClass();
    $Projects = $obj->list();
    
    var_dump($Projects);
    

    Your class:

    class YourClass(){
    
        public function list() {
            $Projects=array();
            if (isset($_GET['employee'])){
                $ProjectEmployees = $this->ProjectEmployeesTable->find('EmployeeID', $_GET['employee']);
                if(count($ProjectEmployees)){ foreach($ProjectEmployees as $ProjectEmploy){
                    $Projects[] = $this->projectsTable->find('ProjectID', $ProjectEmploy->ProjectID);
                }}
            }
            return (object) $Projects;
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog