正在检查用于垂直排序数组值的其他方法,以便在表格中使用,但大多数方法相当于将表格向右翻转90度.我一直试图想办法正确实现这个,但我想我需要一些帮助.
例如,表(水平顺序):
a b c d e
f g h i j
k l m n o
p q r
Run Code Online (Sandbox Code Playgroud)
重新排序(垂直顺序):
a e i m p
b f j n q
c g k o r
d h l
Run Code Online (Sandbox Code Playgroud)
如您所见,由于最后2个单元格为空,因此保留了结构.
不是这样的:
a e i m q
b f j n r
c g k o
d h l p
Run Code Online (Sandbox Code Playgroud)
在这个例子中,该表类似于侧向翻转它.有谁知道如何正确地做到这一点?
编辑:这比我想象的要难,我第一次(或两次)搞砸了。现在应该可以了。
假设您将表结构存储在二维数组中:
$data = array(
array('a', 'b', 'c', 'd', 'e'),
array('f', 'g', 'h', 'i', 'j'),
array('k', 'l', 'm', 'n', 'o'),
array('p', 'q', 'r')
);
Run Code Online (Sandbox Code Playgroud)
由于您想保持相同的“形状”,因此您需要确定桌子的尺寸。为此,我们可以获取count第一行的 ,因为我们知道第一行必须是表格的最大宽度。高度只是数组中元素的数量。
$width = count($data[0]); // 5
$height = count($data); // 4
Run Code Online (Sandbox Code Playgroud)
我们还需要元素的总数,但我们可能会通过采用 $width * $height 来高估。
$total = $width * $height; // 20
Run Code Online (Sandbox Code Playgroud)
然后,只需进行一点数学计算即可计算出事物的去向。我们必须对新旧索引使用单独的计数器,因为一旦开始出现漏洞,我们就必须以不同的方式递增它们。
$new_data = array();
$j = 0;
for($i = 0; $i < $total; $i++) {
$old_x = floor($i / $width); // integer division
$old_y = $i % $width; // modulo
do {
$new_x = $j % $height; // modulo
$new_y = floor($j / $height); // integer division
$j++;
// move on to the next position if we have reached an index that isn't available in the old data structure
} while (!isset($data[$new_x][$new_y]) && $j < $total);
if (!isset($new_data[$new_x])) {
$new_data[$new_x] = array();
}
if (isset($data[$old_x][$old_y])) {
$new_data[$new_x][$new_y] = $data[$old_x][$old_y];
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
629 次 |
| 最近记录: |