iT邦幫忙

2021 iThome 鐵人賽

DAY 3
0
自我挑戰組

從零開始學習php+Laravel 8系列 第 3

[Day 3] php陣列與資料結構

php中陣列的寫法

  • 一般陣列
    其索引值形式為從0開始往後累加的數字(0、1、2、3...)
$fruit1 = ['apple','banana','orange'];
$fruit2 = array('apple','banana','orange');

檢視陣列時可以使用print_r來印出結果。

  • 字典式陣列
    其索引值形式為指定的名稱
$fruits = ['type1' => 'apple', 'type2' => 'banana'];

如何迴圈方式取得陣列中的資料
在php中可以使用foreach迴圈

$fruits = ['apple','banana','orange'];
foreach($fruits as $index => $type){
    echo('第'.$index.'種水果 '.$type."\r\n");
}

$index表示陣列的索引值(位置0、1、2)
$type表示陣列的值(apple、banana、orange)
其中$index、$type變數名稱是可以替換的

取得字典式陣列中的資料

$fruits = [
    ['country' => 'Taiwan','type' => 'bananas'],
    ['country' => 'Japan','type' => 'grapes']
];
foreach($fruits as $key => $value){
    echo('第'.$key.'種水果 '.$value['type']."\r\n");
}

上一篇
[Day 2] php變數型態與運算
下一篇
[Day 4] laravel介紹
系列文
從零開始學習php+Laravel 830
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言