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 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考