2015-04-01 38 views
0

我想用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'] 

它會打印類別標題

你有什麼想法嗎?我從字面上看了好幾個月,無法弄清楚。

+1

Sry基因,但我一點也不都明白自己在做什麼。你能向我們展示一個你想要的結果數組的簡短例子嗎? – Unex 2015-04-01 16:28:23

+0

你確定SQL請求是否涉及到這個問題,或者這只是如何訪問數組中的值? – mins 2015-04-01 18:15:21

回答

1

使用以下命令:

while ($row = mysqli_fetch_assoc($query)) { 
    if (!isset($row['campaign_id'])) { 
     $array[$row['campaign_id']] = $row; 
    } 
    if (!isset($array[$row['campaign_id']]['categories'])) { 
     $array[$row['campaign_id']]['categories'] = array(); 
    } 
    $array[$row['campaign_id']]['categories'][$row['category_id']] = array('category_id' => $row['category_id'], 'category_title' => $row['category_title']); 
    } 
} 

$row已經是一個關聯數組,你不需要每一個元素分別分配。您只需要特別處理類別信息,該信息必須放入我稱爲categories的嵌套關聯數組中。所以,你會訪問它

$array[0]['categories'][1]['category_title'] 

你也可以遍歷所有的類別有:

foreach ($array[$campaign]['categories'] as $cat) { 
    echo "Category ID: {$cat['category_id']} Title: {$cat['category_title']}<br>"; 
} 
+0

非常感謝!如果我們不這樣做,它會好嗎!array_key_exists?這不是更好的選擇嗎? – lancey 2015-04-01 16:49:55

+1

如果你喜歡,你可以使用它。我更喜歡'isset()',因爲它更簡潔,更易於閱讀恕我直言。 – Barmar 2015-04-01 16:51:14

+0

你會如何做一個foreach循環來顯示每個類別的標題? – lancey 2015-04-01 20:01:52