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
.
- You need to store all project in array like: $Projects=array();
- In foreach loop You need to push all project in that
$Projects array. - Then you need to return this array like: return $Projects;.
- 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;
}
}
THIS IS TEMPORARY ANSWER to @rashid to show him how to transform the array from @DavidCasttelanoo into a object. Its not a answer to the original question. Its a Answer to his comment , where he need a object instead of the array
$objectProjects = new $Projects();
foreach ($arrayProjects as $key => $value)
{
$objectProjects->$key = $value;
}
Projects is now a object.