我有两张桌子
第一个表名是“Library”
ID Name
1 A
2 B
第二个表名是“Books”
BID Book_Creater Book_Name
1 Variation1 Book1
1 Variation2 Book2
1 Variation3 Book3
2 Variation1 Book4
2 Variation2 Book5
sql是
$sql = mysql_query("select library.ID,books.Book_Creater,books.Book_name from library,books where library.ID = books.BID;
结果是
ID Book_Creater Book_name
1 Variation1 Book1
1 Variation2 Book2
1 Variation3 Book3
2 Variation1 Book4
2 Variation2 Book5
现在我想创建一个看起来像的数组,这就是我被困住的地方。
array(
[1] => array(
[Variation1] => Book1
[Variation2] => Book2
[Variation3] => Book3
)
[2] => array(
[Variation1] => Book4
[Variation2] => Book5
)
)
任何建议都会很棒。
答案 0 :(得分:3)
$res = array();
//for each result row
while($row = mysql_fetch_array($sql))
{
//add a row to the multi dimensional result array
//where the first key = id and the second key = Book_Creater
$res[$row['id']][$row['Book_Creater']] = $row['Book_name'];
}
print_r($res);
答案 1 :(得分:2)
简单的方法是像现在一样进行连接,并在循环时将它们推入数组中(当ID作为键已经存在时,可能明确地创建新的子数组)。
这样的事情: -
<?php
$store_array = array();
$sql = mysql_query("SELECT library.ID,books.Book_Creater,books.Book_name
FROM library
INNER JOIN books
ON library.ID = books.BID");
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
if (!array_key_exists($row['ID'], $store_array))
{
$store_array[$row['ID']] = array();
}
$store_array[$row['ID']][$row['Book_Creater']] = $row['Book_name']
}
print_r($store_array);
?>
你也可以将一些努力改组到数据库中,然后将事物重新连接起来。然后将结果拆分为数组: -
<?php
$store_array = array();
$sql = mysql_query("SELECT library.ID, GROUP_CONCAT(CONCAT_WS('#~#', books.Book_Creater,books.Book_name)) AS details
FROM library
INNER JOIN books
ON library.ID = books.BID
GROUP BY library.ID");
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
$store_array[$row['ID']] = array();
$details = explode(',', $row['details']);
foreach($details as $detail)
{
$detail_line = explode('#~#', $row['detail']);
$store_array[$row['ID']][$detail_line[0]] = $detail_line[1];
}
}
print_r($store_array);
?>
请注意,如果您使用实际数据执行此操作,则可能需要选择不会出现在数据中的分隔符,并且默认情况下GROUP_CONCAT的最大长度相当有限。
另请注意,我使用了mysql_ *函数,因为您似乎正在使用这些函数,但这些函数已被弃用,现在可能不应该使用。