我想用PHP將所有數據邏輯地存儲在嵌套關聯數組中,然後每當我通過數據循環或需要引用數據時,我會引用數組指針而不是每次都進行新的查詢。將PHP查詢設置爲嵌套數組
例如:
我的查詢是
$query = $db->query("
SELECT
c.id campaign_id,
c.campaign_title,
c.start_date campaign_start_date,
c.end_date campaign_end_date,
cat.id category_id,
cat.category_title,
n.id nominee_id,
n.title nominee_title,
u.id voter_id,
u.fullname voter_name
FROM
campaign c
LEFT JOIN categories cat ON cat.campaign_id = c.id
LEFT JOIN category_nominees cn ON cn.category_id = cat.id
LEFT JOIN nominees n ON n.id = cn.nominee_id
LEFT JOIN category_votes cv ON cv.campaign_id = c.id
AND cv.category_id = cat.id
AND cv.nominee_id = n.id
LEFT JOIN users u on u.id = cv.user_id
WHERE
c.active = 1
ORDER BY
u.fullname,
c.campaign_title,
cat.category_order,
cat.category_title,
cn.nominee_order,
n.title
") or die(mysqli_error());
和IM試圖建立嵌套數組一樣
$array = array() ;
while($row = mysqli_fetch_assoc($query)) {
$array[$row['campaign_id']] = $row['campaign_id'];
$array[$row['campaign_id']]['campaign_title'] = $row['campaign_title'];
$array[$row['campaign_id']]['campaign_start_date'] = $row['campaign_start_date'];
$array[$row['campaign_id']]['campaign_end_date'] = $row['campaign_end_date'];
$array[$row['campaign_id']]['campaign_title'] = $row['campaign_title'];
$array[$row['campaign_id']]['category_id'] = $row['category_id'];
$array[$row['campaign_id']]['category_id']['category_title'] = $row['category_title'];
}
所以每當我指出:
$array[2][3]['category_title']
它會打印類別標題
你有什麼想法嗎?我從字面上看了好幾個月,無法弄清楚。
Sry基因,但我一點也不都明白自己在做什麼。你能向我們展示一個你想要的結果數組的簡短例子嗎? – Unex 2015-04-01 16:28:23
你確定SQL請求是否涉及到這個問題,或者這只是如何訪問數組中的值? – mins 2015-04-01 18:15:21