I have two MySQL tables, both connected via MySQL JOIN:
TableA:
hom_id con_id
3 4
5 3
TableB:
hom_id con_id hp_id
3 4 1
3 4 2
My pseudo PHP Code:
foreach ($hom as $h) //from TableA
echo $h->con_id
---myidea---
foreach ($pro as $p) //from TableB
echo $p->hp_id
endforeach
---END---
endforeach
The HTML result I got is:
Result HTML Table:
con_id hp_id
3 1 2
4 1 2
What I want to have is:
result HTML:
con_id hp_id
3
4 1 2
I am pretty sure, that its just few line of php code which I have to change. But I can't see the answer, please give me a hint how to change it. Thanks
Guess a simple if would solve your problem, if I got ir right.
foreach ($hom as $h) {//from TableA
echo $h->con_id
foreach ($pro as $p) { //from TableB
if ($p->con_id == $h->con_id) {
echo $p->hp_id
}
}
}
Or, maybe you should just handle it in your SQL query, using a LEFT JOIN
You can use following sql statement:
select a.con_id,group_concat(b.hp_id SEPARATOR " ") as hp_id
from tableA a
left join tableB b on(a.hom_id=b.hom_id and a.con_id=b.con_id)
group by a.hom_id,a.con_id
It will give the result as per your requirement.
Why don't you try change your query?
SELECT A.con_id, B.hp_id
FROM A
LEFT JOIN B ON(A.con_id = B.con_id)
And do a simple foreach
foreach($result as $res)
{
echo $res->con_id, $res->hp_id
}
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.