this is our (mysql) database structure and data :
Products:
id | title
1 | samsung galaxy
2 | iphone
Propertise: (note : parent Propertise has parent_id=0)
id | title | parent_id
1 | screen | 0
2 | screen size | 1
3 | screen resolution | 1
Products_Propertise:
id | products_id | propertise_id | value
1 | 1 | 1 | null
2 | 1 | 2 | 5 inch
3 | 1 | 3 | 500 ppi
4 | 2 | 1 | null
5 | 2 | 2 | 4.2 inch
6 | 2 | 3 | 330 ppi
so we need this html output :
<table>
<tr>
<td> Products : </td>
<td> samsung galaxy </td>
<td> iphone </td>
</tr>
<tr class="parent_Propertise">
<td> screen : </td>
<td> null </td>
<td> null </td>
</tr>
<tr>
<td> screen size : </td>
<td> 5 inch </td>
<td> 4.2 inch</td>
</tr>
<tr>
<td> screen resolution : </td>
<td> 500 ppi </td>
<td> 330 ppi</td>
</tr>
</table>
i fetched data in to an array() using this mysql query code :
SELECT Products.name, Products_Propertise.value,Propertise.id,Propertise.title,Propertise.parent_id
FROM Products_Propertise
JOIN Propertise ON Products_Propertise.propertise_id=Propertise.id
JOIN Products ON Products_Propertise.products_id=Products.id
WHERE Products_Propertise.products_id=1 OR Products_Propertise.products_id=2
and i used this recursive function to show data in html table :
<?php
//index elements by id
foreach ($resutls as $item) {
$item['subs'] = array();
$indexedItems[$item['id']] = (object) $item;
}
//assign to parent
$topLevel = array();
foreach ($indexedItems as $item) {
if ($item->parent_id == 0) {
$topLevel[] = $item;
} else {
$indexedItems[$item->parent_id]->subs[] = $item;
}
}
//recursive function
function renderMenu($items) {
$render = "";
$i=0;
foreach ($items as $item) {
if(!empty($item->subs))
{
$i++;
$render .= "<tr class='parent_Propertise'><td>".$item->title."</td><td></td></tr>";
}else{
$render .= "<tr><td>".$item->title."</td><td>".$item->value."</td></tr>";
}
if (!empty($item->subs))
{
$render .= renderMenu($item->subs);
}
}//end foreach
return $render;
}
echo "<table><tr><td>Products :<td>";
foreach ($resutls as $item) {
echo "<td>".$item['name']."<td>";
}
echo "</tr>";
echo renderMenu($topLevel);
echo "</table>";
?>
but final output is not that we want !! can anyone help me?
One problem is that you're not fetching the data out of the results
$resutls = mysqli_query($con,$query);
$resutls
is a mysqli_result object , not an array. You're doing this
foreach ($resutls as $item) {
Instead, what you need is a while
loop
while($item = $resutls->fetch_assoc()) {
Or procedural
while($item = mysqli_fetch_assoc($resutls)) {
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.