gpt4 book ai didi

php表关联

转载 作者:行者123 更新时间:2023-11-29 08:42:37 25 4
gpt4 key购买 nike

我在两个表之间的关联上遇到问题:我有

table 1 "flowers": "id", "flower";
table 2 "colors": "id", "color";
table 3 "association_flowers_colors": "id", "id_flower", "id_color";

现在,一朵花可以有多种颜色,现在的问题是父数组中的所有信息。es:如果我获取第一个表中的所有信息并获取它们,我将拥有

array([0](array[id]=>0, [flower]=>rose), [1]array([id]=>1, [flower]=>tulip));

然后,如果我从第二个表中收集所有信息,我将得到

array([0]array([id]=>0, [color]=>red)[1]), [1]array([id]=>1, [color]=>white));

现在解决问题:我需要按照

的方式获取一个数组
array([0]array([id]=>0, [flower]=>rose, [color]=>red, [color]=>white), [1]array([id]=>1, [flower]=>tulip, [color]=>red, [color]=>white));

是否有一种简单的方法可以使用单个详细查询来完成此操作,或者我应该使用 while 循环或类似的东西,然后合并我得到的信息?

谢谢

编辑:

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;
}

在阅读了 juergen 的回复后,我最终得到了这个,看起来它有效,问题是它为我提供了每种颜色的数组(总共 4 个数组),而不是只给我 2 个包含两种颜色的数组(总共 2 个数组)。

编辑2:好吧,我没有找到一种方法来检索 2 个数组(而不是 4 个)中的所有信息,但我还是设法以可读的方式打印它们:

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'];
}

这样即使循环重复每个数组的所有信息,它也只会在有新条目时输出信息,而不会重复任何内容。

最佳答案

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

关于php表关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13384509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com