2012-07-17 103 views
0

我試圖將值到一個數組,像這樣:如何在PHP中構建一個二維數組?

$scoreValues[$i][] = $percent ; 
$scoreValues[$i][] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ; 

我基本上要到$%的用字符串連接在一起,所以我得到這樣的輸出:

array (0 > array('46.5', '<span etc etc') 

然後我計劃按百分比排序,所以我有最高的得分字符串。

+0

可能重複[如何在PHP中對多維數組進行排序](http://stackoverflow.com/q/96759/),[如何創建多維數組PHP](http:// stackoverflow。 com/q/8638051 /) – outis 2012-07-17 09:01:39

回答

1

最簡單的方法是使用兩個數組

array_multisort(
    $data['percents'], SORT_DESC, 
    $data['scores']); 
+0

不知道array_multisort,對我來說讓事情變得簡單多謝。 – imperium2335 2012-07-17 08:42:45

1

在需要指定所述第二陣列的索引的第二行:

$scoreValues[$i][$j] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ; 

所以你基本上需要2個計數器,一個用於外部陣列($ i)和對內部數組($ j)的。

編輯:

你讓我有點這樣一個問題困惑,好像你需要的是不是多dimensinal陣列,而是一個簡單的數組:

$scoreValues[$percent] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ; 

請注意,這要求$percent是唯一的。使用array_multisort

$percents[$i] = $percent; 
$scores[$i] = "<span....>"); 

或者一個數組,但索引這樣

$data = new arrray('percents' => array(), 'scores' => array()); 
$data['percents'][$i] = $percent; 
$data['scores'][$i] = "<span....>"); 

一旦做到這一點,你再排序的數組:

+0

你的編輯要求'$ percent'是唯一的 - 可以保證嗎? – halfer 2012-07-17 08:40:21

+0

不,你說得對,我會將其添加到答案中。 – Tomer 2012-07-17 08:48:53

+0

謝謝! +1,因爲使用密鑰會簡單得多。 – halfer 2012-07-17 08:54:33

0

試試這個:

$val = array(
    'percent' => $percent, 
    'html' => '<span id="item' . $i . 
       '" class="suggestElement" data-entityid="'.$row['id']. 
       '" data-match="'.$percent.'">'.rawurldecode($row['name']). 
       '</span>' 
); 
// This just pushes it onto the end of the array 
$scoreValues[] = $val ; 
// Or you can insert it at an explicit location 
//$scoreValues[$i] = $val;