我想知道是否有数学家可以帮助我解决以下问题:
我正在试着把数字序列012345678变成036147258。
其目的是对没有标准排序函数的PHP数组的索引进行排序。
这就是我所能得到的:
for($i=0; $i<count($arrayWithNineIndices); $i++)
{
$j=($i%3)*3;
echo $j;
if($i%3===0) echo " <----";
echo "<br />";
}它垂直输出036036036,标记在零上。
理想情况下,我需要的是一种机制,在第一个标记后面的值上加1,然后在第二个标记后的值上加2。
我花了整个上午的时间尝试,主要是使用(j=0; j<3; j++)循环,但没有效果。
发布于 2013-01-08 18:46:42
$result = array();
for ($i = 0; $i < 3; $i++) {
for ($j = $i; isset($array[$j]); $j += 3) {
$result[] = $array[$j];
}
}
print_r($result);发布于 2013-01-08 18:49:08
您可以使用
$str = "012345678";
list($a, $b, $c) = array_chunk(str_split($str), 3);
foreach ( array_map(null, $a, $b, $c) as $part ) {
echo implode($part);
}输出
036147258对于通用函数
echo autoShift("012345678", 3), PHP_EOL;
echo autoShift("0123456", 3), PHP_EOL;
echo autoShift("012345678", 2), PHP_EOL;
echo autoShift("0123", 2), PHP_EOL;输出
036147258
0361425
024681357
0213使用的函数
function autoShift($str, $shift = 3) {
$args = array_chunk(str_split($str), $shift);
array_unshift($args, null);
return implode(array_map("implode", call_user_func_array("array_map", $args)));
}https://stackoverflow.com/questions/14213141
复制相似问题