2
我有一個多對多表中的MySQL - 它可以是這個樣子:MySQL的多對多桌到桌矩陣
A | B
1 | 1
1 | 2
1 | 3
3 | 4
3 | 5
4 | 1
4 | 2
4 | 5
等
你會發現,這些數字並不總是(A = 1,3,4 ..) - 我正在尋找將此轉換爲矩陣表的最快方法,忽略沒有數據的列和行(例如A = 2)。因爲我是把每一行到PHP中一個單獨的陣列,通過嵌套while循環,它檢查要我有工作是痛苦的緩慢如果數組A和數組B匹配當前指數的關鍵是:
while ($i <= $max_A) {
if (in_array($i, $array_A)) {
print ("<tr>");
while ($j <= $max_B) {
if (in_array($j, $array_B)) {
print ("<td>");
if (in_matrix($i, $j, $array_A, $array_B)) {
print ("1");
} else {
print ("0");
}
print ("</td>");
}
$j++;
}
print ("</tr>\n");
$j = $min_B;
}
$i++;
}
function in_matrix($search_value_A, $search_value_B, $array_A, $array_B) {
// Store the array keys matching search
$keys_A = array_keys($array_A, $search_value_A);
$keys_B = array_keys($array_B, $search_value_B);
foreach ($keys_A as $value) {
if (in_array($value, $keys_B)) {
return true;
}
}
return false;
}
也許還有更多的我可以做MySQL側或加快搜索功能 - 我試圖找到一種方法來搜索一個二維數組(例如,如果列A = x和列B = y在給定的行中返回true)。
感謝
'while'循環開始前'$ i'和'$ j'是什麼? – 2009-11-23 00:28:32