2016-07-08 59 views
3

我查詢了數據庫,並將結果存儲到數組中。它看起來像這樣:PHP:用現有唯一值替換數組索引鍵

Array 
(
[0] => Array 
    (
     [Submission_ID] => 111 
     [First_Name] => Dylan 
     [Last_Name] => Taylor 
     [Abstract_Title] => Research 1 
    ) 

[1] => Array 
    (
     [Submission_ID] => 222 
     [First_Name] => Michael 
     [Last_Name] => Jones 
     [Abstract_Title] => Research 2 
    ) 

[2] => Array 
    (
     [Submission_ID] => 333 
     [First_Name] => Wills 
     [Last_Name] => Adams 
     [Abstract_Title] => Research 3 
    ) 
) 

這是全部放在一個名爲$results的變量中。目前,我在我的網頁上顯示的數據位,如下所示:

echo $results[0][Abstract_Title] 

所有的工作,但是,它是方便,如果索引鍵是與提交ID代替:

Array 
(
[111] => Array 
    (
     [Submission_ID] => 111 
     [First_Name] => Dylan 
     [Last_Name] => Taylor 
     [Abstract_Title] => Research 1 
    ) 

[222] => Array 
    (
     [Submission_ID] => 222 
     [First_Name] => Michael 
     [Last_Name] => Jones 
     [Abstract_Title] => Research 2 
    ) 

[333] => Array 
    (
     [Submission_ID] => 333 
     [First_Name] => Wills 
     [Last_Name] => Adams 
     [Abstract_Title] => Research 3 
    ) 
) 

所以我可以這樣做(否則我將不得不打印陣列只是爲了每次查找索引鍵):

echo $results[111][Abstract_Title] 

任何想法? (我是編程新手。)我找到的最接近的答案是:php replace array id keys但我無法解決問題。我想到一個forloop是最好的選擇?新的數組應該放在相同的變量還是新的變量中?

回答

4

您可以簡單地使用array_combinearray_column等作爲

$final_result = array_combine(array_column($result,'Submission_ID'),$result); 
print_r($final_result); 
+1

一個很好的解決方案! –

+0

謝謝@Sougata .... –