2013-01-03 104 views
0

我想要的順序改變:更改陣列順序(如列)

$array = array(
    "a" => "bar", 
    "b" => "foo", 
    "c" => "bar", 
    "d" => "foo", 
    "e" => "bar", 
    "f" => "foo", 
    "g" => "bar", 
    "h" => "foo", 
    "i" => "bar", 
    "j" => "foo" 
); 

要:

$array = array(
    "a" => "bar", "f"=> "foo", 
    "b" => "foo", "g"=> "bar", 
    "c" => "bar", "h"=> "foo", 
    "d" => "foo", "i"=> "bar", 
    "e" => "bar", "j"=> "foo" 
); 

這樣做的一點是,我要填寫一個表中的項目陣列:

陣列不應被排序如下:

<table> 
<tr><td>Item 1</td><td>Item 2</td></tr> 
<tr><td>Item 3</td><td>Item 4</td></tr> 
</table> 

但是這樣的:

<table> 
<tr><td>Item 1</td><td>Item 3</td></tr> 
<tr><td>Item 2</td><td>Item 4</td></tr> 
</table> 

感謝

+1

如果你想在網頁上顯示結果,你需要看看'css',因爲這樣會更適合這份工作。 – jeroen

+0

需要CSS和HTML來輸出列。請具體瞭解更多細節。 –

回答

1

沒有必要重新排列原始數組。只需使用array_chunk將它分成兩對,並在構建html時循環遍歷它們。

$array = array(....); 
$size = ceil(count($array)/2); 
list($left, $right) = array_chunk($array, $size, true); 
echo '<table>'; 
while (count($left) > 0) { 
    echo '<tr>'; 
    echo '<td>', key($left), ': ', array_shift($left), '</td>'; 
    echo '<td>', key($right), ': ', array_shift($right), '</td>'; 
    echo '</tr>'; 
} 
echo '</table>'; 
+0

哦,嘿,我還沒有想到。我認爲這是最簡單的解決方案。謝謝! – user1600804

0

我認爲它不會母校是否關鍵是一個字符串或一個整數。

$array = array(
    4 => 'd', 
    2 => 'b', 
    3 => 'c', 
    6 => 'f', 
    5 => 'e', 
    1 => 'a' 
); 

$x = floor(count($array)/2); 
for($i=1; $i <= $x; $i++) 
{ 
    $array2[ $i ] = $array[ $i ]; 
    $array2[ $i + $x ] = $array[ $i + $x ]; 
} 

將輸出:

$Array2 
(
    [1] => a, [4] => d, 
    [2] => b, [5] => e, 
    [3] => c, [6] => f 
) 

JB