采取以下数组:
$rows = array(
'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5,
'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10
);
我想把它放在一张桌子上,从上到下,从左到右阅读,如下:
a 1 c 3 e 5 g 7 i 9
b 2 d 4 f 6 h 8 j 10
作为我的表创建函数的输入,我需要将数组转换为每个项描述一个表行的数组,如下所示:
Array(
[0] => Array(
a => 1
c => 3
e => 5
g => 7
i => 9
)
[1] => Array(
b => 2
d => 4
f => 6
h => 8
j => 10
)
以下代码是我的尝试,但我无法让它完全运作:
$cols_length = 5;
$rows_length = (int) ceil(count($rows) / $cols_length); // 2
$keys = array_keys($rows);
$values = array_values($rows);
$output = array();
for ($i = 0; $i < $rows_length; $i++) {
for ($j = 0; $j < $cols_length; $j++) {
$key = $i + ($j * $rows_length);
if (array_key_exists($key, $keys)) {
$output[$i][$keys[$i + $j]] = $values[$key];
}
}
}
print_r($output);
现在输出:
Array(
[0] => Array
(
[c] => 1
[d] => 3
[e] => 5
[f] => 7
[g] => 9
)
[1] => Array
(
[d] => 2
[e] => 4
[f] => 6
[g] => 8
[h] => 10
)
)
我做错了什么?
[编辑]
感谢您的回复。它很棒:)但是我犯了一个错误。输出数组应按如下方式构造:
Array (
[0] => Array (
[0] => a
[1] => 1
[2] => c
[3] => 3
[4] => e
[5] => 5
[6] => g
[7] => 7
[8] => i
[9] => 9
)
[1] => Array (
[0] => b
[1] => 2
[2] => d
[3] => 4
[4] => f
[5] => 6
[6] => h
[7] => 8
[8] => j
[9] => 10
)
)
我试图修改代码以支持此输出,但我得到了奇怪的结果。我应该使用额外的$ j ++计数器吗?
$i = 0;
foreach($rows as $key => $value) {
$result[$i++ % 2][] = $key;
$result[$i++ % 2][] = $value;
}
答案 0 :(得分:2)
您可以使用模数运算符(%
)来确定元素是否应位于第一行或第二行:
$rows = array(
'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5,
'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10
);
$result = array();
$i = 0;
foreach($rows as $key => $value) {
if(!isset($result[$i % 2])) {
$result[$i % 2] = array();
}
$result[$i % 2][$key] = $value;
$i++;
}
print_r($result);
工作示例:
即使您需要更多行,也可以将% 2
增加到您需要的行数。