1.写函数创建长度为10的数组,数组中的元素为递增的奇数,首项为1.
function createArr($first,$length){
for($i=$first;$i<=$length;$i++){
$num = 2*$i-1;
$arr[] = $num;
}
return $arr;
}
print_r(createArr(1,10));
2.创建长度为10的数组,数组中的数为递增的等比数,比值为3,首项为1.
function createArr($ratio,$length){
$num = 1/$ratio;
for($i=1;$i<=$length;$i++){
$num = $num*$ratio;
$arr[] = $num;
}
return $arr;
}
print_r(createArr(3,10));
3.求数组中最大数的下标.
function maxkey($arr){
$maxval = max($arr);
foreach($arr as $key=>$val){
if($maxval == $val){
$maxkey = $key;
}
}
return $maxkey;
}
$arr = array(0,-1,-2,5,15,3);
echo maxkey($arr);
4.创建一个长度为10的数组,数组中的元素满足斐波拉契数列的规律.
function arrFibo($n){
for($i=0;$i<$n;$i++){
if($i<2){
$arr[$i] = 1;
}else{
$arr[$i] = $arr[$i-1] + $arr[$i-2];
}
}
return $arr;
}
print_r(arrFibo(8));
5.写一个方法,将一个长度超过10的数组最后5项直接截取,不改变顺序变为前5项,如{1,2,3,4,5,6,7,8,9,10}变为{6,7,8,9,10,1,2,3,4,5}.
function arrsort($arr){
$num = count($arr);
if($num > 10){
//array_slice($arr,起始位置,截取长度,保留索引(默认为false))
$arr_firstpart = array_slice($arr,0,$num-5,true);
$arr_lastpart = array_slice($arr,($num-5),5,true);
}else{
echo "数组不超过10个元素,请重新输入";
exit();
}
//拼接
$arr_new = array_merge($arr_lastpart,$arr_firstpart);
return $arr_new;
}
$arr = array("a"=>1,2,3,8,9,6,"b"=>5,-1,"c"=>8,0,7);
echo "<pre>";
print_r($arr);
echo "<br>= = = = = 拼接后 = = = = <br><br>";
print_r(arrsort($arr));
echo "</pre>";6.将两个数组连接成一个新数组. $arr = array("a"=>1,"b"=>2,3);
$arr2 = array("a"=>Dee,3,5);
$arr3 = array_merge($arr,$arr2);
$arr4 = array_merge_recursive($arr,$arr2);
echo "<pre>";
print_r($arr3);
echo "<br> = = = = = <br><br>";
print_r($arr4);
echo "</pre>";
7.将两个数组连成一个新数组
$arr = array("a"=>1,"b"=>2,3);
$arr2 = array("a"=>"zou",3,5);
$arr3 = array_merge($arr,$arr2);
$arr4 = array_merge_recursive($arr,$arr2);
echo "<pre>";
print_r($arr3);
echo "<br> = = = = = <br><br>";
print_r($arr4);
echo "</pre>";
8.数组逆序( 不能使用rsort函数,不能生成新数组 )
$arr = array("a","b","c",1,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 "<pre>";
print_r($arr);
echo "</pre>";
9.PHP数字金额转换成大小格式 function daxie($num){
$da_num = array("零","一","二","三","四","五","六","七","八","九");
$str = ‘‘;
if(is_numeric($num) && strlen($num)>0){
for($i=0;$i<strlen($num);$i++){
$str .= $da_num[substr($num,$i,1)];
}
}
return $str;
}
echo daxie(1896);