php學習(1)

小溪彼岸發表於2016-06-26

php的簡單定義:
      PHP是一種伺服器端HTML-嵌入式指令碼描述語言。

php基本語法:

  • php 陣列

a. 陣列的建立和賦值

    <?php
      $arr = array();
      $arr['t1'] = 'test1';
      $arr['t2'] = 'test2';
      $arr['t3'] = 'test3';
      print_r( $arr['t1'].$arr['t2'].$arr['t3']);
    ?>
     <br>
    <?php
      $vegetables =  array();
      $vegetables[0] = "yellow";
      $vegetables[1] = "red";
      $vegetables[2] = "orange";
      echo $vegetables[0];
    ?>
     <br>
    <?php
      $vegetables =  array("a"=> "abc","b"=>"black","c"=>"color");
      echo $vegetables["a"];
    ?>

陣列demo:

 <?php
        $row_color = array('red','green');
        $color_index = 0;
        $meal = array('早餐'=>'油條,雞蛋,豆漿',
                      '午餐'=>'套餐,快餐',
                      '晚餐'=>'沙拉,香檳,拉麵',
                      '夜宵'=>"混沌,烤肉串");
        print '<table border="1"><caption>本店提供</caption>';
        foreach($meal as $key => $value){
            print "<tr bgcolor='".$row_color[$color_index]."'>";
            print "<td>$key</td><td>$value</td></tr>";
            $color_index = 1 - $color_index;
        }
        print "</table>";
     ?>

效果截圖:
這裡寫圖片描述

b. 判斷陣列中是否存在鍵值

   // demo1
   <?php
    $meals = array('麵條',
        '饅頭',
    '餃子',
    '大餅'
    );
    echo "<br>";
    if(in_array('麵條',$meals)){
    print $meals[0];
    }
    ?>

    // demo2
     <?php
        $meals = array('麵條'=>5.0,
                       '饅頭'=>2.0,
                       '餃子'=>8.0,
                       '大餅'=>3.0,
        );
        $books = array('book1','author');
       if(array_key_exists('麵條',$meals)){
           print "吃麵條<br/>";
       }
      if(array_key_exists('餃子',$meals)){
          print "吃餃子<br/>";
      }
      if(array_key_exists(1,$books)){
          print  $books[0]."的作者是:".$books[1]."";
      }
      ?>

c.陣列的遍歷

<!--陣列的遍歷-->
<?php
  $arr = array('麵條','雞蛋','油條');
  for($i = 0;$i<count($arr);$i++){
      echo $arr[$i]."<br>";
  }
  echo "<hr>";
  foreach($arr as $value){
      echo  $value."<br>";
  }
?>

d.利用implode把陣列轉換為字串

<?php
//利用implode來生成字串
$meals = array('麵條', '饅頭', '餃子', '大餅');
echo implode('<><>',$meals);
?>

轉換結果:

麵條<><>饅頭<><>餃子<><>大餅

demo:

<?php
//利用implode來生成字串
$meals = array('麵條', '饅頭', '餃子', '大餅');
$price = array('18','19','20','20');
echo "<table border='1'><tr><td>";
echo implode('</td><td>',$meals)."</td></tr>";
echo "<tr><td>".implode("</td><td>",$price)."</td></tr>";
echo "</table>";
?>

轉換結果:
這裡寫圖片描述

e.對陣列進行排序

<?php
$meals = array('麵條', 'a饅頭', '餃子', '大餅');
$price = array('28','1','22','20');
foreach($meals as $value ){
    echo $value."<br>";
}
foreach($price as $value ){
    echo $value."<br>";
}

sort($meals);
sort($price);

foreach($meals as $value ){
    echo $value."<br>";
}
foreach($price as $value ){
    echo $value."<br>";
}

?>