i have a problem with an association between 2 tables:
i have
table 1 "flowers": "id", "flower";
table 2 "colors": "id", "color";
table 3 "association_flowers_colors": "id", "id_flower", "id_color";
now, a single flower can have many colors, now the problem is the father all the informations inside a single array.
es: if i get all the informations inside the first table and fetch them i’m gonna have
array([0](array[id]=>0, [flower]=>rose), [1]array([id]=>1, [flower]=>tulip));
then if i gather all the informations from the second table i’m gonna have
array([0]array([id]=>0, [color]=>red)[1]), [1]array([id]=>1, [color]=>white));
Now to the problem: i’d need to get an array along the lines of
array([0]array([id]=>0, [flower]=>rose, [color]=>red, [color]=>white), [1]array([id]=>1, [flower]=>tulip, [color]=>red, [color]=>white));
is there a simple way to do it with a single elaborated query or should i go with while loop or something like that and then merge the informations i get?
Thanks
edit:
function get_flowers(){
include('../actions/db_connection.php');
$result = mysqli_query($db_connection, "select *
from flowers f
left outer join association_flowers_colors a on f.id = a.id_flower
left outer join colors c on c.id = a.id_color");
mysqli_close($db_connection);
$flowers = array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$flowers[] = $row;
};
return $flowers;
}
I ended up with this after reading juergen’s reply, it looks like it works the problem is that it gives me an array for each color(for a total of 4 arrays) instead of giving me only 2 arrays with both colors inside(for a total of 2 arrays).
edit2:
Ok, i didnt find a way to retrieve all the informations in 2 arrays(instead of 4) but i managed to print them in a readable way anyway:
while($row = mysqli_fetch_array($flowers)){
if ($flowerID != $row['id_flower']) {
echo "<div class='flowerContainer'>";
echo "<input type='hidden' name='flowerID' value='".$row['id_flower']."'>";
echo "Name: ".$row['flower']."<br />";
}
echo $row['color']."<br />";
if ($flowerID == $row['id_flower']) {
echo "</div>";
echo "<hr>";
}
$flowerID = $row['id_flower'];
}
in this way even if the loop repeats all the information for every array, it will only output the information if there’s a new entry and it won’t repeat anything.
1 Answer