I have two tables connected in a different way than I want them, and I will try my best to explain what I am searching for, together with what I have accomplished myself so far.
What I am searching for: First of all, I have a table objects_price
and a table materials
. These tables are shown beneath:
objects_price
:
materials
:
Okay so I have some objects which can be a chair, table or whatever furniture you can imaging. All objects are connected to a third table with information about the object. Each object requires some sort of material in order to be crafted. As you can see in the objects_price
table, the object with an id
of 1 requires 47 of the material equal to 1. Which is Oak Log
as you can see in the materials
table.
The object with an id of 2 requires two materials, material 2 and 3. and it requires 20 of Stone
and 30 of Birch log
To make everything a little more clear, heres an image displaying what I just explained:
What I have so far is two queries where one of them doesn't do what I want it to, especially because I am using an array to display the materials and the amount but what my code does is that it displays all of the materials in all of the objects, it looks like this right now:
The problem lies in this query and the way it creates an array:
$query = 'SELECT objects_price.object_id, materials.material_id, materials.name, material_amount
FROM objects_price
LEFT JOIN materials USING(material_id)';
$result = $mysqli->query($query);
$arr = array();
while($row = $result->fetch_assoc()) {
$arr[$row['name']][] = $row['material_amount'];
}
together with the way I provide the objects with their corresponding materials:
foreach($arr as $name => $objects) {
?>
<p><?php echo $name; ?><i style="float:right;"><?php foreach($objects as $material_amount) { echo $material_amount; } ?></i></p>
<?php
}
I hope I made it clear and please tell me if you want me to provide more code, more images or explanation or anything like that. Any help, advice or suggestions are highly appreciated. Thanks for your time.
while($row = $result->fetch_assoc()) {
$arr[$row['object_id']][$row['name']] = $row['material_amount'];
}
....
foreach ($arr as $key){
$material_array = $key;
foreach ($material_array as $k => $v){
echo "<p>$k | $v</p>";
}
It will display material name and amount correctly, but there are no names of objects themselves.
}