1 创建数组
# 创建空数组 $arr = array(); var_dump( $arr ); echo '<br>'; $arrs = []; var_dump( $arrs ); echo '<hr>';
2 关联数组、索引数组
# 创建索引数组 # 键从0开始,没有给默认键,叫索引数组 (键为数字) $arr = [ 10, 11, '欧阳克', '朱老师', 19.99, null ]; print_r($arr); echo '<hr>'; # print_r专门打印数组的值,不是数组也可打印,不能在正式环境中使用 # 创建关联数组 $arr = [ '23001' => '合肥1', '23002' => '合肥2', '23003' => '合肥3', '23004' => '合肥4', ]; print_r( $arr ); echo '<hr>'; # 索引 (键/下标) 可以是数字,也可以string,也可汉字,但不建议用,可能会有字符集问题
3 访问数组的数据
$arr = [ 10, 11, '欧阳克', '朱老师', 19.99, null ]; echo $arr[3]; echo '<br>'; $arr = [ '23001' => '合肥1', '23002' => '合肥2', '三区' => '合肥3', '四区' => '合肥4', ]; echo $arr['23001']; echo $arr['三区']; echo '<hr>';
4 二维数组、三维数组
# 1、二维数组 $arr = [ [ 'name' => '欧阳克', 'age' => 18, 'job' =>'PHP讲师' ], [ 'name' => '朱老师', 'age' => 60, 'job' =>'PHP讲师' ], [ 'name' => '西门大官人', 'age' => 17, 'job' =>'PHP讲师' ] ]; print_r($arr[1]['name']); echo '<br>'; # 2、三维数组 $arr = [ [ 'name' => '欧阳克', 'age' => 18, 'job' =>'PHP讲师', 'skill' => [ 'php', 'html', '小程序', ] ], [ 'name' => '朱老师', 'age' => 60, 'job' =>'PHP讲师', 'skill' => [ 'html', 'css', 'js', ] ], [ 'name' => '西门大官人', 'age' => 17, 'job' =>'PHP讲师' ] ]; print_r($arr[0]['skill']); echo '<hr>';
5 二维数组循环,三维数组循环
$arr3 = [ [ 'name' => '欧阳克', 'age' => 18, 'job' =>'PHP讲师' ], [ 'name' => '朱老师', 'age' => 60, 'job' =>'PHP讲师' ], [ 'name' => '西门大官人', 'age' => 17, 'job' =>'PHP讲师' ] ]; foreach($arr3 as $val){ // print_r($val); // echo '<br>'; foreach($val as $vv){ echo $vv; echo '<br>'; } } echo '<hr>'; # 二维数组用两次foreach不好,占用服务器内存,且无法控制取出单独的数组 foreach($arr3 as $val){ print_r($val['name']); echo '<br>'; } echo '<hr>'; $arr4 = [ [ 'name' => '欧阳克', 'age' => 18, 'job' =>'PHP讲师', 'skill' => [ 'php', 'html', '小程序', ] ], [ 'name' => '朱老师', 'age' => 60, 'job' =>'PHP讲师', 'skill' => [ 'html', 'css', 'js', ] ], [ 'name' => '西门大官人', 'age' => 17, 'job' =>'PHP讲师', 'skill' => [ '实战', 'php', 'html', ] ] ]; foreach($arr4 as $val){ echo '姓名:' .$val['name']. '---'; echo '年龄:' .$val['age']. '---'; echo '职业:' .$val['job']. '---'; echo '技能:'; foreach($val['skill'] as $vv){ echo $vv . '-'; } echo '<br>'; } echo '<hr>';