PHP打印环状数圈

如题:
int i=[number];
打印如下的图形:

1  2  3  4
12 13 14 5
11 16 15 6
10 9  8  7

PHP代码如下

 

function sort_recursive(&$array){
    foreach($array as $key=>$edge){
        ksort($edge,true);
        $array[$key]=$edge;
    }
    ksort($array,true);
}

function generate(&$container,$start_value,$x,$grids_edge){
    $rec_times=ceil($grids_edge/2);
    $center=$grids_edge&1?false:$start_value+4*$rec_times*($rec_times+1);
    if($center){
        $index=$x+ceil($grids_edge/2);
        $container[$index][$index]=$center;
    }
	for($i=0;$i<$grids_edge;$i++){
	    $right=$x+$grids_edge;
	    $basevalue=$start_value+$i;
	    $container[$x][$x+$i]=$base_value;
	    $container[$x+$i][$right]=$grids_edge+$base_value;
	    $container[$right][$right-$i]=$grids_edge*2+$base_value;
	    $container[$right-$i][$x]=$grids_edge*3+$base_value;
	}
}


$container=array();
$data=array(
    1 =>array(1,6),
    25=>array(2,4),
    41=>array(3,2),
);
/*
$data=array(
    1 =>array(1,2),
);
$data=array(
    1 =>array(1,5),
    21=>array(2,3),
    33=>array(3,1),
);
$data=array(
	1 =>array(1,3),
	13=>array(2,1),
);
*/
foreach($data as $key=>$val){
    generate($container,$key,$val[0],$val[1]);
}
sort_recursive($container);
$table='<table border=1>';
foreach($container as $key=>$edge){
	$table.='<tr>';
	foreach($edge as $val){
        $table.='<td>'.$val.'</td>';
    }
    $table.='</tr>';
}
$table.='</table>';
echo $table;

你可能感兴趣的:(PHP)