我的任务是按升序和降序对数字数组进行排序。挑战在于,我不能使用内置的排序函数,而是使用for循环遍历数组。
当涉及到PHP时,我完全是一个新手,这项任务直接把我搞糊涂了。下面是我应该使用的代码:
<?php
$arr = $_GET['arr'];
$table = explode(',', $arr);
$count = count($table);
// What I tried to work with, didn't get to work:
for ($i = 0; $i < $count; $i++) {
for ($j = $i + 1; $j < $count; $j++) {
if ($table[$i] > $table[$j]) {
$temp = $table[$i];
$table[$i] = $table[$j];
$table[$j] = $temp;
$asc = implode("," $temp);
}
}
}
echo "Ascending: $asc";
echo "Descending: $desc";
?>你知道为什么这个不能运行吗?在某种程度上,我得到了带有echo的数组中的第一个(最大的)数字,但也不知道是什么打破了这一点。
发布于 2021-10-13 19:29:20
移动线条
$asc = implode(",", $table);从外部for循环下面的当前位置开始,可能会添加下面这一行
$desc = implode(",", array_reverse($table));来获得降序排序。
发布于 2021-10-13 19:49:29
有很多方法可以做到这点。您将在下面的代码中找到一个解决方案。您肯定会注意到排序只依赖于一个运算符。因此,您可以通过将排序指定为参数来构建一个函数。function(array $array, string $sort) {}
描述
$arr= array(112,21,130,140,2,42);
for($i=0; $i<count($arr)-1; $i++)
{
for($j=0; $j<count($arr)-1; $j++)
{
if($arr[$j] < $arr[$j+1]){
$temp= $arr[$j+1];
$arr[$j+1]= $arr[$j];
$arr[$j]= $temp;
}
}
}
print_r($arr);输出:
Array
(
[0] => 140
[1] => 130
[2] => 112
[3] => 42
[4] => 21
[5] => 2
)ASC
$arr= array(112,21,130,140,2,42);
for($i=0; $i<count($arr)-1; $i++)
{
for($j=0; $j<count($arr)-1; $j++)
{
if($arr[$j] > $arr[$j+1]){
$temp= $arr[$j+1];
$arr[$j+1]= $arr[$j];
$arr[$j]= $temp;
}
}
}
print_r($arr);输出
Array
(
[0] => 2
[1] => 21
[2] => 42
[3] => 112
[4] => 130
[5] => 140
)https://stackoverflow.com/questions/69560888
复制相似问题