我已经问过类似的问题,但我需要不同的效果。原来的问题是here .
我有一个简单的数组。数组长度始终是一个平方数。所以 16、25、36 等。
$array = array('1', '2', '3', '4' ... '25');
我所做的是用 HTML 排列数组,使其看起来像一个具有偶数边的 block 。
我想做的是对元素进行排序,这样当我将 JSON 编码的数组传递给 jQuery 时,它会迭代该数组,在当前 block 中淡入淡出,这样我就会得到一个圆形动画。所以我想像这样对数组进行排序
所以我的排序数组看起来像
$sorted = array('1', '6', '11'', '16', '21', '22', '23' .. '13');
有办法吗?...谢谢
编辑:
我试图通过创建类似矩阵的列/行数组来做到这一点:
$side = 5;
$elems = $side*$side;
$array = range(1,$elems);
for($i=1; $i <= $side; $i++) {
for($x=$i; $x <= $elems; $x=$x+$side) {
$columns[$i][] = $x;
}
}
for($i=1, $y=1; $i <= $elems; $i=$i+$side, $y++) {
for($x=$i; $x < $side+$i; $x++) {
$rows[$y][] = $x;
}
}
我的下一步是沿着第一列向下走,最后如果它正好在最后一个元素列上,最后在最后一个元素上等等。如果有人有更好的主意那就太好了:)
最佳答案
只要网格始终是正方形,这就可以工作:
<?php
// The size of the grid - 5x5 in the example above
$gridSize = 5;
// Create a 2D array representing the grid
$elements = array_chunk(range(1, pow($gridSize, 2)), $gridSize);
// Find the half way point - this will be the end of the loop since we
// want to stop in the middle
$end = ceil($gridSize / 2);
// An array to hold the result
$result = array();
// The stopping point of the current interation
$stop = $gridSize;
// Loop from start to the middle
for ($i = 0; $i < $end; $i++) {
// start in the top left corner
$x = $y = $i;
// Traverse Y top to bottom
while ($y < $stop) {
$result[] = $elements[$y++][$x];
}
$y--;
$x++;
// Traverse X left to right
while ($x < $stop) {
$result[] = $elements[$y][$x++];
}
$x--;
$y--;
// Traverse Y bottom to top
while ($y >= $gridSize - $stop) {
$result[] = $elements[$y--][$x];
}
$y++;
$x--;
// Make sure we come in a level
$stop--;
// Traverse X right to left
while ($x >= $gridSize - $stop) {
$result[] = $elements[$y][$x--];
}
}
print_r($result);
关于PHP 元素数组,按循环 "animation"排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15203482/