well,
I've got 3 tables with foreign keys on similar words:
assignment :
idassignment,
idshift
idworker
shift :
idshift
name
worker :
idworker
name
I made a select (using joins where needed) that takes all of the relevant data from them.
I want to make an array that resembles the DB's structure.
today I just iterate over assignments, and use keys from that table
to look into shift and worker.
any comment would help.
example:
(ignore fields not specified in the end example) I use this SQL:
SELECT
`assignment`.`assignmentid`,
`assignment`.`date`,
`assignment`.`shiftid`,
`assignment`.`workerid`,
`shift`.`ShiftsID`,
`shift`.`WorkersNum`,
`shift`.`ShiftsType`,
`shift`.`length`,
`worker`.`WorkerID`,
`worker`.`FirstName`,
`worker`.`LastName`,
`worker`.`Email`,
`worker`.`phone`
FROM `mydb`.`assignment` LEFT JOIN `mydb`.`shift` ON ShiftsID=shiftid
LEFT JOIN `mydb`.`worker` USING (`workerid`)
with this data:
assigment
(1,1,1),
(2,2,1),
(3,2,2)
shift
(1,"morning")
(2,"lunch")
worker
(1,"john")
(2,"doe")
and I want the array to look like:
Array
{
[0]=>Array
{
[assignmentID]==>1;
[shift]==>Array
{
[shiftid]=1;
[name]="morning";
}
[worker]==>Array
{
[idworker]=1;
[name]="john";
}
}
[1]=>Array
{
[assignmentID]==>2;
[shift]==>Array
{
[shiftid]=2;
[name]="lunch";
}
[worker]==>Array
{
[idworker]=1;
[name]="john";
}
}
[2]=>Array
{
[assignmentID]==>3;
[shift]==>Array
{
[shiftid]=2;
[name]="lunch";
}
[worker]==>Array
{
[idworker]=2;
[name]="doe";
}
}
}
I just used a function for each table which returns me the array for it.
function shift(id)
function worker(id)
and I traverse assignment between dates. and call those and put them all into an array;
$sql = /* your sql statement */;
if (($data = mysql_query($sql)) !== false)
{
$details = array();
while (($row = mysql_fetch_array($data)) !== false)
{
$details[] = array(
'assignmentID' => $row['assignmentid'],
'shift' => array(
'shiftid' => $row['ShiftsID'],
'name' => // i don't see `shift`.`name`, but that goes here
),
'worker' => array(
'idworker' => $row['WorkerID'],
'name' => $row['FirstName']
)
);
}
// $details is now populated with the structure you were looking for.
}
Something like that? Though your initial database column names and those in your query don't align, so I'm a little confused. Made a best-guess for that.
EDIT
Could also get more creative and check if worker/shift are supplied (given a left join) and then only add the array information for them when results are returned in the query. eg
$details[] = array(
'assignmentID' => $row['assignmentid']
'shift' => (!is_null($row['ShiftsID'])?array(
...
):null), // null when there's no shift
'worker' => (!is_null($row['WorkerID'])?array(
...
):null) // null when there's no worker
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.