3 回答

TA貢獻(xiàn)1772條經(jīng)驗 獲得超8個贊
如果您使用 mysqli,那么您可以使用fetch_all()和 來完成此操作array_column()。這將生成一個數(shù)組,其中每個元素都是來自數(shù)據(jù)庫的標(biāo)簽。如果您使用 PDO 會容易得多,我強(qiáng)烈建議您在還不算太晚的情況下進(jìn)行切換。
要使用 mysqli 執(zhí)行此操作,您可以這樣做:
$stmt = $mysqli->prepare(
'SELECT tagid
FROM entitytag
WHERE audioid = ?
ORDER BY tagid
LIMIT 3'
);
$stmt->bind_param('s', $audioid);
$stmt->execute();
$tags = array_column($stmt->get_result()->fetch_all(), 0);
// Either loop on all 3 tags assigning each to a variable
foreach ($tags as $tag) {
echo $tag;
}
// or access each one via its index. 0 = first tag, 1 = second tag, 2 = third tag
echo $tags[1] ?? 'No tag!';
您可以通過使用數(shù)字索引循環(huán)數(shù)組來訪問數(shù)組變量中的元素。如果您決定使用索引,請確保提供默認(rèn)值,以防數(shù)組中的標(biāo)簽少于 3 個。使用?? 'default'語法。

TA貢獻(xiàn)1797條經(jīng)驗 獲得超6個贊
這可行,但不確定如何預(yù)測將擁有的變量數(shù)量,我仍然更喜歡堅持使用數(shù)組而不將其內(nèi)容提取到變量中。
/// assign inside while loop
$tags[] = $row->tag;
// use variables outside the loop
list($tag1, $tag2, $tag3) = $tags;

TA貢獻(xiàn)1865條經(jīng)驗 獲得超7個贊
將結(jié)果放入關(guān)聯(lián)數(shù)組中
$array = [];
$i = 1;
while($row=findTag1Result->fetch_assoc()) {
$array['tag' . $i] = $row;
$i++;
}
然后使用 extract 來獲取變量。
extract($array);
- 3 回答
- 0 關(guān)注
- 138 瀏覽
添加回答
舉報