有关php数组及循环的小例子

WBOY
Freigeben: 2016-07-25 09:05:14
Original
1036 人浏览过
  1. //1、使用循环语句,输出任意一个二维数组 。

  2. $arr=array(
  3. array(1,2,3,4),
  4. array(5,6,7,8),
  5. array(9,10,11,12),
  6. array(13,14,15,16)
  7. );
  8. foreach ($arr as $var){
  9. foreach ($var as $val1){
  10. echo "$val1 ";
  11. }
  12. echo "
    ";
  13. }
  14. echo "
    ";

  15. //2、使用循环控制语句,输出杨辉三角。
  16. function yanghuisanjiao($line){
  17. $sc[][]=array();
  18. $sc[0][0]=1;
  19. for($i=1;$ifor($j=0;$jif($j==0 or $i==$j){
  20. $sc[$i][$j]=1; //把每行的第一个数字和最后一个数字设为1
  21. }else{
  22. $sc[$i][$j]=$sc[$i-1][$j-1]+$sc[$i-1][$j];
  23. }
  24. }
  25. }
  26. foreach ($sc as $value){
  27. foreach($value as $v1){
  28. echo $v1.' ';
  29. }
  30. echo '

    ';

  31. }
  32. }
  33. yanghuisanjiao(5);

  34. echo "
    ";

  35. //3、使用循环和预定义变量,获取多个参数。参数的个数未定。
  36. function avg(){
  37. $ags=func_get_args();
  38. $sum=0;
  39. foreach ($ags as $v){
  40. $sum+=$v;
  41. }
  42. return '平均值是:'.$sum/func_num_args();
  43. }
  44. echo avg(1,2,3,4,5,6,7);
  45. //4、使用循环输出一个二维数组,并求该矩形对角线元素的和。
  46. function getSum($theCount){
  47. $b=0;
  48. echo '';
  49. echo "";
  50. for($i=1;$iecho "
  51. ";
  52. for($j=1;$j if($j==$i || $theCount+1-$i==$j){
  53. echo "
  54. ";
  55. $b=$b+$j;
  56. if($j==$i && $theCount+1-$i==$j){
  57. $b=$b+$j;
  58. }
  59. }
  60. else{
  61. echo "
  62. ";
  63. }
  64. }
  65. echo "
  66. ";
  67. }
  68. echo "
  69. $j $j
    ";
  70. echo "对角线元素之和为:".$b;
  71. }
  72. getSum(6);
  73. ?>
  74. 复制代码猜你喜欢: php 数组递归求和的例子


Verwandte Etiketten:
Quelle:php.cn
Vorheriger Artikel:php出现Notice : Use of undefined constant 的解决方法 Nächster Artikel:php下ddos攻击与防范代码
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Aktuelle Ausgaben
verwandte Themen
Mehr>
Beliebte Empfehlungen
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!