PHP
function arrsub($arr){
sort($arr);
$min = $arr[0];
rsort($arr);
$max = $arr[0];
$sub = $max - $min;
return $sub;
}
$arr = array(-1,100);
echo arrsub($arr);
PHP
function arrsort($arr){
$num = count($arr);
if($num > 10){
//array_slice($arr,起始位置,截取长度,保留索引(默认为false))
$arr_firstpart = array_slice($arr,$num-5,true);
$arr_lastpart = array_slice($arr,($num-5),true);
}else{
echo "数组不超过10个元素,请重新输入";
exit();
}
//拼接
$arr_new = array_merge($arr_lastpart,$arr_firstpart);
return $arr_new;
}
$arr = array("a"=>1,"b"=>5,"c"=>8,7);
echo "
";
print_r($arr);
echo "
= = = = = 拼接后 = = = =
";
print_r(arrsort($arr));
echo "
";
1
[0] => 2
[1] => 3
[2] => 8
[3] => 9
[4] => 6
[b] => 5
[5] => -1
[c] => 8
[6] => 0
[7] => 7
)
5
[0] => -1
[c] => 8
[1] => 0
[2] => 7
[a] => 1
[3] => 2
[4] => 3
[5] => 8
[6] => 9
[7] => 6
)
方法②使用array_merge_recursive()函数递归追加数组
( array_merge_recursive() 函数与 array_merge() 函数 一样,将一个或多个数组的元素的合并起来,一个数组中的值附加在前一个数组的后面。并返回作为结果的数组。
但是,与 array_merge() 不同的是,当有重复的键名时,值不会被覆盖,而是将多个相同键名的值递归组成一个数组。)
PHP
$arr = array("a"=>1,"b"=>2,3);
$arr2 = array("a"=>Dee,5);
$arr3 = array_merge($arr,$arr2);
$arr4 = array_merge_recursive($arr,$arr2);
echo "
";
print_r($arr3);
echo "
= = = = =
";
print_r($arr4);
echo "
";
输出:
Dee
[b] => 2
[0] => 3
[1] => 3
[2] => 5
)
= = = = =
Array
(
[0] => 1
[1] => Dee
)
[b] => 2
[0] => 3
[1] => 3
[2] => 5
)
第一个输出的数组中索引为"a"的值1被索引被第二个数组中索引为"a"的值Dee覆盖了。
PHP
function arrsort($arr1,$arr2){
$arr_new = $arr1;
foreach($arr2 as $key=>$val){
$arr_new[] = $val;
}
return $arr_new;
}
$arr1 = array("a"=>1,3);
$arr2 = array("a"=>Dee,"c"=>3,5);
echo "
";
print_r(arrsort($arr1,$arr2));
echo "
";
输出:
1
[b] => 2
[0] => 3
[1] => Dee
[2] => 3
[3] => 5
)
如果是索引数组而且有重复的索引,则第二个数组中的这个重复的索引会被
修改成新的索引。
8.数组逆序( 不能使用rsort函数,不能生成新数组 )
使用array_reverse()函数会创建新的数组,所以不能使用。
PHP
$arr = array("a","b","c",10);
$i = "";//要替换位置的数的下标
$j = "";//临时变量
$k = "";//被替换位置的数的下标
$len = count($arr);
$half_len = floor($len/2);//向下取整,取整的值是循环的次数
for($i=0;$i<$half_len;$i++){
$j = $arr[$i];
//判断数组个数奇偶
if($len%2!=0){ //奇数
$k = $half_len*2-$i;
}else{
//偶数
$k = $half_len*2-$i-1;
}
$arr[$i] = $arr[$k];
$arr[$k] = $j;
}
echo "
";
print_r($arr);
echo "
";
输出:
10
[1] => 1
[2] => c
[3] => b
[4] => a
)