1使用PHP的排序函数对以下中的数组排序。 2.在表单上由用户输入学号,姓名和成绩这三列的数据,一共5行。

2024-11-23 03:55:55
推荐回答(2个)
回答1:

费了一段时间,总算完成这个作业,也算是一种锻炼吧,以下是代码,虽然感觉效率比较低,为什么不用数据库呢?


header('Content-type:text/html;charset=utf-8');
//2维数组排序
function sysSortArray($ArrayData, $KeyName1, $SortOrder1 = "SORT_ASC", $SortType1 = "SORT_REGULAR")
{
if (!is_array($ArrayData)) {
return $ArrayData;
}

// Get args number.
$ArgCount = func_num_args();

// Get keys to sort by and put them to SortRule array.
for ($I = 1; $I < $ArgCount; $I++) {
$Arg = func_get_arg($I);
if (!eregi("SORT", $Arg)) {
$KeyNameList[] = $Arg;
$SortRule[] = '$' . $Arg;
} else {
$SortRule[] = $Arg;
}
}

// Get the values according to the keys and put them to array.
foreach ($ArrayData as $Key => $Info) {
foreach ($KeyNameList as $KeyName) {
${$KeyName}[$Key] = $Info[$KeyName];
}
}

// Create the eval string and eval it.
$EvalString = 'array_multisort(' . join(",", $SortRule) . ',$ArrayData);';
eval($EvalString);
return $ArrayData;
}

$keys = array('stu_no','name','price');

//输出表格
echo "请输入需要排序的数据:
";
echo "

";
echo "";
echo "";
for ($row = 1; $row < 6; $row++) {
echo "";
for ($col = 1; $col < 4; $col++) {
echo "";
}
echo "";
}
echo "
学号姓名成绩
";
echo "";
echo "
";

//转换数组
if (isset($_POST['bt'])) {
for ($row = 1; $row < 6; $row++)
for ($col = 1; $col < 4; $col++) {
$key = $keys[$col-1];
$stu[$row][$key] = $_POST['stu_' . $row . '_' . $col];
}
echo '
';
print_r($stu);
echo '
';

}

//排序
$temp = sysSortArray($stu,'price',"SORT_ASC");

echo '
';
print_r($temp);
echo '
'

?>

回答2:

echo "请输入需要排序的数据:";
echo "

"; //新建表单
for($i=1;$i<6;$i++) //循环生成文本框
{
//文本框的名字是数组名
echo "";
}
echo ""; //提交按钮
echo "
";
if(isset($_POST['bt'])){
$sum=0;
$stu=$_POST['stu']; //取得所有文本框的值并赋予数组$stu
$num=count($stu); //计算数组$stu元素个数
echo "您输入的数据有:
";
foreach($stu as $score){
echo $score."
"; //输出接收的值
$sum=$sum+$score;
}
echo "排序后的数据为:
";
function bubbleSort($arr)
{
// 外层循环控制需要比较的轮数
for ($i = 1, $len = count($arr); $i < $len; ++$i) {
for ($j = 0; $j < $len - $i; ++$j) { // 内层循环控制参与比较的元素
if ($arr[$j] > $arr[$j + 1]) { // 比较相邻的两个元素
$temp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $temp;
}
}
}
return $arr;
}

$sort=bubbleSort($stu);
foreach ($sort as $sco){
echo $sco."
";
}

echo "5个数据和为:".$sum."
";
echo "5个数据平均数为:".$sum/$num."
";
}
?>