排序数组,没有php内置的排序函数



我是编程新手,第一次学习关于数组的PHP语言。我可以用sort函数对数组进行排序,但我被卡住了。

如果我输入了array(1,3,5,6,7,8,11,12,17,11)我试图得到输出12或更大的数字2,但如果我得到print_r($array[i] - 1);我刚拿到10-1=9。如何获取值12

然后如果我有输入CCD_ 7,由于缺少数字4,我尝试得到输出CCD_。我做排序功能:

for(int j:0;j<=count($array) ;j++) {
for(int i:0;i<=count($array[i+1]);i++{
if($array[i]>$array[$+1]{
$temp=$array[$i+1];
$array[$i+1]=$array[$i];
$array[$i]=temp;
}
}
}
print_r($array) ;

如果有人能帮我或教我,谢谢你?:(

您的代码中有很多语法错误。检查你的问题下的评论,他们几乎涵盖了它。

要使用自定义排序对数组进行排序,可以使用以下方法:

$array = array(1,3,5,6,7,8,11,12,17,11);
$arrayCount = count($array);  // no need to evaluate the count on every iteration of the for loop
for($i=0; $i < $arrayCount - 1; $i++)
{
for($j = $i+1; $j < $arrayCount; $j++)
{
// if you want the array sorted from bigger to smaller number use `>` here
if($array[$j] < $array[$i])
{
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
}
}
}
print_r($array);

输出:

Array
(
[0] => 1
[1] => 3
[2] => 5
[3] => 6
[4] => 7
[5] => 8
[6] => 11
[7] => 11
[8] => 12
[9] => 17
)

现在,要从数组或false中检索所需的值(如果它不存在(,您可以使用内置的array_search()方法编写如下内容:

// Check if array contains a value 12, if it does return the index location in the array
// returns false if the value is not found
$index = array_search(12, $array); 
if($index === false)
{
echo 'Value does not exist in the array.';
}
else
{
echo 'Value '.$array[$index].' is at index '.$index.' in the array.';
}

最新更新