2012-07-04 27 views
1

鍵列1我有一個包含從mysql查詢中創建數組。列2爲作爲價值

column 1 = state column 2 = link 
Alabama    auburn.alabama.com 
Alabama    bham.alabama.com 
Alabama    dothan.alabama.com 

我需要從我的數據庫表中抓住並放入數組,我可以array_walk()通過一個表。他們需要像這個數組一樣訪問。

$arraytable = array(
"auburn.alabama.com"=>"Alabama", 
"bham.alabama.com"=>"Alabama", 
"dothan.alabama.com"=>"Alabama", 
); 

我已經嘗試了一切,但不知道如何使這個工作使用PHP來打印這樣的數組。任何幫助是極大的讚賞。

回答

2

注意您的問題標題與您的示例不一致。在標題中你要求列1作爲鍵,但你的例子使用列2作爲鍵。我在這裏使用了第2列......

您不清楚使用什麼MySQL API來獲取,但使用哪一個,使用關聯獲取方法並使用$arraytable[$newkey] = $newvalue模式創建新的數組鍵。這個例子是在面向對象的MySQLi:

$arraytable = array(); 

while($row = $result->fetch_assoc()) { 
    // Create a new array key with the 'link' and assign the 'state' 
    $arraytable[$row['link']] = $row['state']; 
} 
+0

出色答卷!效果很好。正準備發佈我的解決方案,並看到這個答案更簡單。這是周圍最大的資源。感謝您的快速響應。 – d3vo

0

您可以使用array_column對於這一點,因爲PHP5.5(http://php.net/array_column

說明

陣列array_column(數組$陣列,混合$ column_key [,mixed $ index_key = null])

array_column()從column_key標識的數組的單個列中返回值。或者,您可以提供一個index_key,以通過輸入數組中index_key列的值爲返回數組中的值建立索引。

對於PHP < 5.5: https://github.com/ramsey/array_column/blob/master/src/array_column.php

+0

注:我意識到這是一個老問題,但有人將鏈接粘貼到IRC作爲他們問題的交叉引用。所以我認爲在這裏引用新功能對未來用戶會很有用。 – AcidReign