编辑:这比我想象的更难,我第一次(或两个)搞砸了。它现在应该工作。
比方说,你已经存储在一个二维数组你的表结构:
$data = array(
array('a', 'b', 'c', 'd', 'e'),
array('f', 'g', 'h', 'i', 'j'),
array('k', 'l', 'm', 'n', 'o'),
array('p', 'q', 'r')
);
既然你想保持相同的“形”,你需要确定表的尺寸。要做到这一点,我们可以取第一行的count
,因为我们知道第一行必须是表的最大宽度。高度只是数组中元素的数量。
$width = count($data[0]); // 5
$height = count($data); // 4
我们也需要元素的总数,但我们可以高估$ width * $ height。
$total = $width * $height; // 20
然后,它真的只是一个小数学来计算事情的发展。我们必须为旧的和新的指数使用单独的计数器,因为一旦我们开始出现漏洞,我们将不得不以不同的方式增加它们。
$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];
}
}
你想从数据库中呈现表中的值? –
是的,但是你可以保持简单并且在这个例子中使用一个数组:'array('a','b','c','d','e'...)'。 – enchance