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>

谢谢

4

2 回答 2

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>';
于 2013-01-03T13:57:15.527 回答
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

于 2013-01-03T13:53:37.313 回答